【发布时间】:2015-03-11 22:32:05
【问题描述】:
您好,我是 Android 的新手,我想知道如何在迭代列表视图时更改列表项的背景颜色。我在 stackoverflow 上看了 4 天,但没有找到适合我的情况的解决方案。
这是我的代码:
public class ExercisesActivity extends ListActivity implements AdapterView.OnItemClickListener {
private static final String TAG="ExerciseActivity";
private static final int REQ_ADD_EXERCISE =1;
private static final int REQ_RENAME_EXERCISE=2;
private String exercise;
private long itemId;
SimpleCursorAdapter adapter;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercises);
lv=getListView();
lv.setOnItemClickListener(this);
Cursor cursor = getContentResolver().query(Exercise.CONTENT_URI, new String[]{Exercise.Columns._ID, Exercise.Columns.EXERCISE_NAME, Exercise.Columns.DONE_LAST},
"",null, Exercise.Columns.DONE_LAST);
adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,
new String[] { Exercise.Columns.EXERCISE_NAME, Exercise.Columns.DONE_LAST},
new int[]{ android.R.id.text1, android.R.id.text2},1);
this.setListAdapter(adapter);
}
@Override
protected void onResume() {
this.setBackgroundColors();
super.onResume();
}
这是我的 setBackgroundColors 方法:
public void setBackgroundColors(){
View listItem;
TextView tv;
for (int i =0;i<lv.getCount();i++){
//listItem=lv.getChildAt(i); --> doesnt work
listItem=lv.getAdapter().getView(i,null,lv);
tv = (TextView) listItem.findViewById(android.R.id.text2);
String color =calculateColor(tv.getText().toString());
Log.d(TAG,color);
if(color.equals("green")){
listItem.setBackgroundColor(getResources().getColor(R.color.green));
}else if(color.equals("yellow")){
listItem.setBackgroundColor(getResources().getColor(R.color.yellow));
}else if (color.equals("red")){
listItem.setBackgroundColor(getResources().getColor(R.color.red));
}
}
}
代码看起来很适合我。 “calculateColor”返回一个有效的字符串值(绿色、黄色、红色)。我已经在 colors.xml 中创建了这些资源颜色。调试时没有错误,代码正在运行,但列表项不会更改其主题颜色。也许主题颜色总是覆盖以编程方式设置的颜色?我必须以这种方式调整一些东西吗?
非常感谢您的帮助!!! :)
【问题讨论】:
标签: android listview adapter background-color