简体   繁体   English

ListView OnClickItems 更改 Android 中的项目颜色

[英]ListView OnClickItems change item color in Android

I'm beginner of android studio.我是 android 工作室的初学者。 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 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.

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