我正在尝试开发一个通用数组适配器类,我喜欢继承奇数行和偶数行的行颜色属性。我的通用适配器类是
public class SpecialAdapter<T> extends ArrayAdapter<T> {
private int[] colors = new int[] { 0x30FF0000, 0x300000FF };
public SpecialAdapter(Context context, int resource, List<T> items) {
super(context, resource,items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int colorPos = position % colors.length;
view.setBackgroundColor(colors[colorPos]);
return view;
}
}
我想将它扩展到我的Adapter类来改变行颜色。
公共类MyArrayAdapter扩展了SpecialAdapter {..}
有可能吗?目前它没有显示任何颜色。我没有在Adapter类中设置任何颜色。我需要的是继承基类的行颜色,以便我可以将它用于不同的Adapter类。
这是我的适配器类
public MyArrayAdapter(Activity context, List<MyObject> list) {
super(context, R.layout.mylayout, list);
this.context = context;
this.list = list;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.mylayout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.txtName = (TextView) view.findViewById(R.id.label);
view.setTag(viewHolder);
} else {
view = convertView;
((ViewHolder) view.getTag()).txtName.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.txtName.setText("Position " + position);
return view;
}
答案 0 :(得分:1)
据我所知,没有这样的通用方法。如果只有2种颜色,则可以使用以下内容。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position % 2 == 1) {
view.setBackgroundColor(Color.BLUE); // you can add any color here
} else {
view.setBackgroundColor(Color.CYAN); // don't like cyan? add another color.
}
return view;
}
答案 1 :(得分:0)
我做了一些调整,因为includeMe建议并且现在正在进行中。我可以将我的布局作为动态传递。
public class SpecialAdapter<T> extends ArrayAdapter<T> {
private int[] colors = new int[] { 0x30FF0000, 0x300000FF };
int resource;
Activity context;
List<T> items;
public SpecialAdapter(Activity context, int resource, List<T> items) {
super(context, resource, items);
this.resource = resource;
this.context = context;
this.items =items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// View view = super.getView(position, convertView, parent);
View view = context.getLayoutInflater().inflate(resource, null);
int colorPos = position % colors.length;
view.setBackgroundColor(colors[colorPos]);
return view;
}
}
并在我的Adapter类getView方法中添加了这一行。
view = super.getView(position, convertView, parent);
替换此行。
view = context.getLayoutInflater().inflate(R.layout.mylayout, null);
现在我不需要在每个适配器类中保留颜色更改代码。超类将负责这一点。