android listview、GridView中item点击后改变其他item中的状态 setOnItemClickListener onItemClick

来源:互联网 发布:汽车app软件下载 编辑:程序博客网 时间:2024/04/27 12:41

先看效果:


item的xml文件如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <CheckedTextView        android:id="@+id/item_grid_tvShow"        android:layout_width="match_parent"        android:layout_height="40dp"        android:background="@drawable/ware_house_filter_bg"        android:gravity="center"        android:checkMark="@null"        android:text="测试"        android:textSize="14sp" /></LinearLayout>
背景颜色设置:

ware_house_filter_bg.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_checked="true" android:drawable="@drawable/ware_house_filter_bg_selected"></item>    <item android:state_pressed="true" android:drawable="@drawable/ware_house_filter_bg_selected"></item><item android:state_checked="false" android:drawable="@drawable/ware_house_filter_bg_unselect"></item>    </selector>
ware_house_filter_bg_selected
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item><shape>            <solid android:color="#f9b800" />            <stroke android:width="1dp" android:color="#f9b800" />            <corners android:radius="5dp" />        </shape></item></selector>

ware_house_filter_bg_unselect.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item><shape>            <solid android:color="#e5e5e5" />            <stroke android:width="1dp" android:color="#e5e5e5" />            <corners android:radius="5dp" />        </shape></item></selector>
添加适配器:

item_area = new ArrayList<>();item_type = new ArrayList<>();for (int i = 0; i < 19; i++) {HashMap<String, String> map = new HashMap<>();HashMap<String, String> map2 = new HashMap<>();map.put("itemName", "区域 " + i);map2.put("itemName", "类型 " + i);item_area.add(map);item_type.add(map2);}// 区域adapterArea = new SimpleAdapter(WareHouseFragment.this.getActivity(), item_area,R.layout.item_text_grid, new String[] { "itemName" },new int[] { R.id.item_grid_tvShow });gv_area.setAdapter(adapterArea);
增加点击事件:

private int indexArea = -1;gv_area.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(android.widget.AdapterView<?> parent,View view, int position, long id) {// TODO Auto-generated method stubif (indexArea != -1) {CheckedTextView tvShowClose = (CheckedTextView) parent.getChildAt(indexArea).findViewById(R.id.item_grid_tvShow);tvShowClose.setChecked(false);}indexArea = position;CheckedTextView tvShow = (CheckedTextView) view.findViewById(R.id.item_grid_tvShow);if (tvShow.isChecked()) {tvShow.setChecked(false);} else {tvShow.setChecked(true);}}});







0 0
原创粉丝点击