public class ListView extends ListActivity {
static String item;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Str.S);
setListAdapter(adapter);
}
这是我的列表视图类,它工作得很好,它从一个名为Str的类中获取字符串并在列表视图中显示它们,问题是列表视图样式不好,它是黑色的,字符串为白色。
我希望它们可以替代每一行都有颜色。
我尝试了很多教程,但没有一个很清楚.. 如何为每行制作替代颜色.. ex。 row1蓝色,第2行白色,第3行蓝色,第4行白色等。
答案 0 :(得分:88)
Here是如何做到的。
我的示例代码简要说明:
覆盖适配器中的getView
方法:
@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);
} else {
view.setBackgroundColor(Color.CYAN);
}
return view;
}
覆盖ArrayAdapter
并覆盖那里的getView方法。
所以,如果您的适配器是这样的:
public class MyAdapter extends ArrayAdapter
您的ListActivity
会改变如下:
ArrayAdapter<String> adapter = new MyAdapter<String>(this,
android.R.layout.simple_list_item_1, Str.S);
Here's an example关于重写ArrayAdapter。
答案 1 :(得分:3)
if (position % 2 == 0) {
rowView.setBackgroundColor(Color.parseColor("#A4A4A4"));
} else {
rowView.setBackgroundColor(Color.parseColor("#FFBF00"));
}
答案 2 :(得分:1)
可以使用
设置自定义列表视图行的背景颜色row.setBackgroundResource(R.color.list_bg_2)
中自定义列表视图适配器中的方法
getView(int position, View convertView, ViewGroup parent)
我尝试了很多像row.setBackgroundColor(0xFF00DD)
这样的东西但是无法完成它,
这里list_bg_2是一个颜色集res / values / color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="list_bg_1">#ffffff</color>
<color name="list_bg_2">#fef2e8</color>
</resources>
答案 3 :(得分:0)
如果view是ViewGroup,简单的背景设置不起作用
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int rr = (position % 2 == 0) ? R.color.border_end_1 : R.color.black;
final int cc = getResources().getColor(rr);
View view = super.getView(position, convertView, parent);
walk(view, rr, cc);
return view;
}
private void walk(View view, int rr, int cc){
view.setBackgroundResource(rr);
ViewGroup group = (ViewGroup)view;
int nc = group.getChildCount();
for (int i = 0; i < nc; i++) {
final View v = group.getChildAt(i);
if (v instanceof ViewGroup)
walk(v, rr, cc);
else
v.setBackgroundColor(cc);
}
}