Java android listView单击后,选择消失

时间:2017-08-28 08:10:41

标签: java android listview

我想这样做:我有一个列表,其中每两个项目的颜色不同,并且想要选择被点击的项目。选中的项目会突出显示,但旧颜色会在释放后返回

我这样做了: artists_list_background_alternate.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

 <item
     android:state_selected="false"
     android:state_pressed="false"
     android:drawable="@color/sign_out_color" />

 <item android:state_pressed="true"
     android:drawable="@color/survey_toplist_item" />

 <item android:state_selected="true"
     android:state_pressed="false"
     android:drawable="@color/survey_toplist_item" />

</selector> 

artists_list_backgroundcolor.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/grey" android:state_pressed="false" android:state_selected="false" />
    <item android:drawable="@color/survey_toplist_item" android:state_pressed="true" />
    <item android:drawable="@color/survey_toplist_item" android:state_pressed="false" android:state_selected="true" />
    <item android:drawable="@color/survey_toplist_item" android:state_pressed="false" android:state_selected="true" />
</selector> 

Java文件代码::

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.listitem, parent, false);
        }

        if (position % 2 == 0) {
            view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
        } else {
            view.setBackgroundResource(R.drawable.artists_list_background_alternate);
        }

        ((TextView) view.findViewById(R.id.heading)).setText(data.get(position));

        return view;
    }


  ListView lvMain = (ListView) findViewById(R.id.list);
        lvMain.setAdapter(adapter);

布局xml ::

 <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="#00000000"
        android:dividerHeight="1dp" />

而且我不知道自己做错了什么

1 个答案:

答案 0 :(得分:0)

要突出显示某个项目,您需要为managementModal提供 choiceMode 。例如:

ListView

另外,在选择器中为状态android:choiceMode="singleChoice" 添加颜色。