我正在用来自ArrayList的字符串填充列表视图。 当单击列表视图项时,我想将背景色更改为绿色。 <-第一个问题,因为我无法更改被单击的项目。
单击一个项目后,我将其索引添加到用户选择的项目列表中,当第一次加载listview时,我需要它将所有被选中的listview项目的背景色也设置为绿色。 。 <-第2期问题-我一直在尝试使用for循环执行此操作,但不知道如何在列表视图中引用特定项来设置背景颜色!
从本质上讲,我认为如果有人可以帮助我如何更改所选列表视图项的颜色,我应该能够做同样的事情,但是循环保存的所有userFoodPref都是这样?
animalsNameList = new ArrayList<String>();
userFoodPref = new ArrayList<Integer>();
getUserSelection();
getAnimalNames();
// Create The Adapter with passing ArrayList as 3rd parameter
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, animalsNameList);
// Set The Adapter
animalList.setAdapter(arrayAdapter);
// register onClickListener to handle click events on each item
animalList.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
// argument position gives the index of item which is clicked
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(userFoodPref.contains(i)
){
userFoodPref.remove(i);}
else {
userFoodPref.add(i);
View item = animalList.getSelectedView();
item.setBackgroundColor(0x0000FF00);
}
String selectedAnimal=animalsNameList.get(i);
Toast.makeText(getApplicationContext(), "Animal Selected : "+selectedAnimal, Toast.LENGTH_LONG).show();
}
});
}
答案 0 :(得分:0)
If I understand well, the problem is that when you set the backround of the item and then by example scroll the list and comeback to the previous position, it doens't remember that the backround is green for this specifix item.
I have faced this problem and to solve it easily :
Create a list a string for your name and a boolean (true = green, false = not green) and create an adapter for it and simply add if (list.get(position).getBoolean) { Currentitem.setBackgroundColor(0x0000FF00)}
And when you click on a item simply set the boolean of the item position to true and call notifydatasetchanged()