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
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
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);
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.