给选中的Item添加效果(For API 11+):
Set list view to single choice:
<ListView android:choiceMode="singleChoice" />
Set the background of the root element of your item layout to your selector:
<LinearLayout android:background="@drawable/selector">
Change android:state_selected to android:state_activated:
1 2 3 4 5
| <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/list_item_selected_color" android:state_activated="true"/> <item android:drawable="@color/list_item_default_color"/> </selector>
|
Highlight item using listView.setItemChecked(index, true);
Note: To make it clear regarding view’s states, specially state_activated you can check this post; it is interesting.
下面是给GridView默认第二项选中的例子:
Activity.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_list);
long cuttStamp = System.currentTimeMillis(); dateList = new ArrayList<Map<String, Object>>(); for (int i = 0; i < 4; i++) { Map<String, Object> item = new HashMap<String, Object>(); item.put("date", DateUtils.getMonDay(cuttStamp)); item.put("week", DateUtils.getWeek(cuttStamp)); dateList.add(item); cuttStamp += 24 * 3600 * 1000; }
simple = new SimpleAdapter(this, dateList, R.layout.item_grid_date, new String[]{"date", "week"}, new int[]{R.id.tv_date, R.id.tv_week}); gridView.setAdapter(simple); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int postion, long id) { gridView.getChildAt(postion).setSelected(true); } }); gridView.post(new Runnable() { @Override public void run() { gridView.performItemClick(gridView.getChildAt(1), 1, gridView.getItemIdAtPosition(1)); }
}); }
|
item_grid_date.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?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:background="@drawable/list_item_color_bg" android:orientation="vertical">
<TextView android:id="@+id/tv_week" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:gravity="center" android:text="abc" />
<TextView android:id="@+id/tv_date" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:gravity="center" android:text="abc" /> </LinearLayout>
|
list_item_color_bg.xml
1 2 3 4 5 6
| <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_activated="true" android:drawable="@color/blue"></item> <item android:drawable="@color/white"></item> </selector>
|