Reputation: 81
I want to change the color background of only one item of the listView, I currently have 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);
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);
Explanation: I have a list of associated accounts owned by a user, I need to change the background color of the account that is active at that moment, the problem is that:
view.setBackgroundResource(R.color.colorPrimaryDark);
Is setting more than one element of the listView, thank you.
Upvotes: 1
Views: 1647
Reputation: 2375
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);
Upvotes: 3
Reputation: 647
Try omitting p
and it's condition.
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);
Upvotes: 0
Reputation: 1618
You need to add a "else" branch in your condition
if (c.getNumber().equals(accountNumber)){
view.setBackgroundResource(R.color.colorPrimaryDark);
} else {
view.setBackgroundResource(R.color.white);
}
Upvotes: 0