我需要多次更改 ListView 的背景颜色,但我不知道如何在单击 ListView 之前获取 ListView 的颜色。
我有这个代码:
if(colores.get(i).equals("0"))
{
listView.getChildAt(i).setBackgroundColor(Color.GREEN);
}
else if(colores.get(i).equals("1"))
{
listView.getChildAt(i).setBackgroundColor(Color.RED);
}
else if(colores.get(i).equals("2"))
{
listView.getChildAt(i).setBackgroundColor(Color.YELLOW);
}
else
{
listView.getChildAt(i).setBackgroundColor(Color.WHITE);
}
我可以更改颜色,但当我单击 ListView 的一项时,我还需要更改颜色,但我不知道如何知道它之前的颜色。
有人可以帮助我吗?谢谢! :)
最佳答案
执行此操作:更改颜色然后创建处理程序。另外,将 View View 设置为最终 View View 。您可以根据子项的位置(即项目的位置)执行 if/else 语句或 switch 语句。
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
view.setBackgroundColor(Color.RED); //on click change to red
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
view.setBackgroundColor(Color.WHITE); //after click changes to white
}
};
handler.postDelayed(runnable, 200); //change to white after 200ms
}
});
//DO THIS BELOW FOR SPECIFIC ITEM IN LISTVIEW
private final String currentColor_P1; //current background color for item at position 1
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
if (position == 1) {
view.setBackgroundColor(Color.BLUE);
} else if (position == 2) {
view.setBackgroundColor(Color.YELLOW);
} else {
view.setBackgroundColor(Color.RED);
}
//OR check for position and check for the known color that you have set for that position
if(position == 1 && currentColor_P1 == BLUE) {
view.setBackgroundColor(Color.YELLOW);
} else if(position == 1 && currentColor_P1 == RED) {
view.setBackgroundColor(Color.YELLOW);
}
//Change color to whatever after clicked and after initial color change happened
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
view.setBackgroundColor(Color.WHITE);
//or
if(position == 1){
view.setBackgroundColor(Color.BLUE)
currentColor_P1 = "BLUE"; //now you set the current backgound for item at position 1 to "blue"
}
}
};
handler.postDelayed(runnable, 200);
}
});
关于java - 获取 ListView 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849130/