简体   繁体   中英

ListView OnClickItems change item color in Android

I'm beginner of android studio. I want to know how to change the color if I click again the selected items on listview, Let say I click the first item it turns the background to color red and it will remain same to the other items but then my problem is when I click the red item again I want to change it to color blue. Below is my sample code it only remain the color when I click the item I have no idea to change it to color blue. Thanks in advance.

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM