简体   繁体   English

如果未选中列表视图中的项目,如何在列表视图中更改背景颜色

[英]How to change background colour in List view if the item in list view is unselected

I am working in android to develop an app which contains a list view in which the background colour of the particular item is changed when the item is clicked ( which is already performed using "ListSelector" in .xml file). 我在android中开发一个应用程序,其中包含一个列表视图,单击该项目时特定项目的背景色会更改(已使用.xml文件中的“ ListSelector”执行了此操作)。 Now I need to deselect the item which I done through " mListview.clearChoices()". 现在,我需要取消选择通过“ mListview.clearChoices()”完成的项目。 But background colour of the previously selected item is not changed. 但是先前选择的项目的背景色不会更改。 Can you guys give some solution ? 你们能给些解决办法吗?

Here is my xml code: 这是我的xml代码:

<ListView
          android:id="@+id/listView"
          android:layout_width="@dimen/dp_130"
          android:layout_height="wrap_content"
          android:background="@color/malibu"
          android:gravity="center"
          android:minHeight="@dimen/dp_50"
          android:listSelector="#e60b62da"/>

Here is the code in Activity file: 这是活动文件中的代码:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                check = 1;
                item_position=position;
                Toast.makeText(MacroActivity.this, "Item clicked_ macro" + position, Toast.LENGTH_SHORT).show();
                item_value = (String) mListView.getItemAtPosition(position);
                Toast.makeText(MacroActivity.this, "Item clicked_ macro_value" + item_value, Toast.LENGTH_SHORT).show();
                    mListView.clearChoices();
            }
        });

When you select a list item view (into onItemClick method) you can set a variable in your adapter to keep selected list item index. 当选择列表项视图(进入onItemClick方法)时,可以在适配器中设置一个变量以保留选定的列表项索引。 Then you can call notifyDatasetChange() . 然后,您可以调用notifyDatasetChange() In your adapter where you create and set your list item views properties you can check if selected index correspond with current selected view. 在您创建并设置列表项视图属性的适配器中,您可以检查所选索引是否与当前所选视图相对应。 In that case you can set a colour, otherwise you can set another one. 在这种情况下,您可以设置一种颜色,否则可以设置另一种颜色。

Hope that helps 希望能有所帮助

This is one of the feasible solution which can be used to solve the above question. 这是可以用来解决上述问题的可行解决方案之一。 I used the listview.setSelector() in which the background colour assigned for the item in the listview can be nullified, yet this function does not allow to set background colour for another item in the listview if needed so. 我使用了listview.setSelector(),其中可以为列表视图中的项目分配背景色,但是该功能不允许在需要时为列表视图中的另一个项目设置背景色。

mListView.setSelector(new ColorDrawable(0)); mListView.setSelector(new ColorDrawable(0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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