【发布时间】:2014-07-22 08:49:37
【问题描述】:
谁能告诉我如何在 android 中为自定义列表视图的列表项赋予两种不同的颜色? 像下图。有可能吗?
请给点建议
感谢您宝贵的时间!..
【问题讨论】:
-
是的。这是可能的。发布您的 ListView 代码。
标签: android listview background-color
谁能告诉我如何在 android 中为自定义列表视图的列表项赋予两种不同的颜色? 像下图。有可能吗?
请给点建议
感谢您宝贵的时间!..
【问题讨论】:
标签: android listview background-color
这段代码会帮助你,
将此代码插入您的自定义列表适配器,
public class ListAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
List<String> data;
ListAdapter(Context context, List<String> data) {
ctx = context;
this.data = data;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.listitem, parent, false);
}
// The logic is added here
if (position % 2 == 0) {
view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
} else {
view.setBackgroundResource(R.drawable.artists_list_background_alternate);
}
((TextView) view.findViewById(R.id.yourText)).setText(data.get(position));
return view;
}
}
【讨论】:
.setBackgroundColor(.....) 而不是 .setBackgroundResource(....)
在您的适配器(BaseAdapter)中使用它:
@Override
public View getView(final int position, View v, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.layout, null);
if (position % 2 == 0) {
yourView.setBackground("First Color ");
} else {
yourView.setBackground("second Color ");
}
return v;
}
【讨论】:
只需在自定义列表适配器的 getView() 方法中打勾即可使用此代码:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder = new ViewHolder();
if (v == null) {
Logger.show(Log.INFO, TAG, " getview v = null");
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.categories_list_item, null);
if (position % 2 == 0) {
v.setBackground(getResources().getColor(R.color.red_color));
// Declare red_color in color.xml as: <color name="red_color">#DF0101</color>
} else {
v.setBackground(getResources().getColor(R.color.blue_color));
// Declare blue_color in color.xml as: <color name="blue_color">#FFFFFF</color>
}
} else {
holder = (ViewHolder) v.getTag();
}
return v;
}
【讨论】: