我想更改listView的一个项目的颜色背景,我目前有这个:
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(parentActivity, android.R.layout.simple_list_item_1, accountList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
ViewGroup.LayoutParams params = view.getLayoutParams();
view.setLayoutParams(params);
TextView textview = (TextView) view;
textview.setTextSize(15);
textview.setGravity(Gravity.CENTER);
textview.setTextColor(Color.WHITE);
int p = 0;
for (Accounts c : Register.getAccounts()) {
if (c.getNumber().equals(accountNumber) && (position == p)){
view.setBackgroundResource(R.color.colorPrimaryDark);
}
p++;
}
return textview;
}
};
listView.setAdapter(adapter);
说明:我有一个用户拥有的关联帐户列表,我需要更改当时活动帐户的背景颜色,问题是:
view.setBackgroundResource(R.color.colorPrimaryDark);
设置listView的多个元素,谢谢。
答案 0 :(得分:2)
i changed your code try this
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(parentActivity, android.R.layout.simple_list_item_1, accountList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
ViewGroup.LayoutParams params = view.getLayoutParams();
view.setLayoutParams(params);
TextView textview = (TextView) view;
textview.setTextSize(15);
textview.setGravity(Gravity.CENTER);
textview.setTextColor(Color.WHITE);
if (Register.getAccounts().get(position).getNumber().equals(accountNumber) ){
textview.setBackgroundResource(R.color.colorPrimaryDark);
}else textview.setBackgroundResource(0);
return textview;
}
};
listView.setAdapter(adapter);
答案 1 :(得分:0)
尝试省略p
及其条件。
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(parentActivity, android.R.layout.simple_list_item_1, accountList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
ViewGroup.LayoutParams params = view.getLayoutParams();
view.setLayoutParams(params);
TextView textview = (TextView) view;
textview.setTextSize(15);
textview.setGravity(Gravity.CENTER);
textview.setTextColor(Color.WHITE);
if (Register.getAccounts().get(position).equals(accountNumber)){
view.setBackgroundResource(R.color.colorPrimaryDark);
}
return textview;
}
};
listView.setAdapter(adapter);
答案 2 :(得分:0)
您需要添加&#34;否则&#34;在你的条件分支
if (c.getNumber().equals(accountNumber)){
view.setBackgroundResource(R.color.colorPrimaryDark);
} else {
view.setBackgroundResource(R.color.white);
}