[英]ListView OnClickItems change item color in Android
public class MainActivity extends AppCompatActivity {
ListView list_view;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_view = (ListView) findViewById(R.id.list_views);
list.add("Data 1");
list.add("Data 2");
list.add("Data 3");
list.add("Data 4");
list.add("Data 5");
adapter =new ArrayAdapter<String>(this, R.layout.list_item,list);
list_view.setAdapter(adapter);
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) {
v.setBackgroundColor(Color.RED);
}
});
}
}
Save the currenly applied color in a variable.将当前应用的颜色保存在变量中。
int currentColor = Color.white; // make this a class variable
int color = currentColor == white ? Color.RED : Color.Blue;
v.setBackgroundColor(color);
PS this is a pseudo code just to explain the idea PS这是一个伪代码,只是为了解释这个想法
There are couple of ways to achieve this, this simplest one is you can check you background color in if condition before apply red color有几种方法可以实现这一点,最简单的一种是您可以在应用红色之前在 if 条件下检查背景颜色
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) {
if (R.color.blue === ((ColorDrawable) v.getBackground()).getColor()) {
v.setBackgroundColor(Color.RED);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.