今天在看android sample中NotePad的代码,突然想给NotesList中的list item添加一个单选效果:
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.v(TAG, "choice mode = " + l.getChoiceMode());
getListView().setItemChecked(position, true);
Log.v(TAG, "checked item = " + l.isItemChecked(position));
return;
/*// Constructs a new URI from the incoming URI and the row ID
Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
// Gets the action from the incoming Intent
String action = getIntent().getAction();
// Handles requests for note data
if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
// Sets the result to return to the component that called this Activity. The
// result contains the new URI
setResult(RESULT_OK, new Intent().setData(uri));
} else {
// Sends out an Intent to start an Activity that can handle ACTION_EDIT. The
// Intent's data is the note ID URI. The effect is to call NoteEdit.
startActivity(new Intent(Intent.ACTION_EDIT, uri));
}*/
}
item view有关,list view会在check某个item时,自动设置这个item view 的check状态,所以最终显示的应该是这个item view在checked状态时的图像。因此,为了达到UI上checked的效果,我们必须选用合适的item view,如果选用系统的,我选择使用 android.R.layout.simple_list_item_activated_1,代码如下:
// Creates the backing adapter for the ListView.
SimpleCursorAdapter adapter
= new SimpleCursorAdapter(
this, // The Context for the ListView
android.R.layout.simple_list_item_activated_1,//R.layout.noteslist_item, // Points to the XML for a list item
cursor, // The cursor to get items from
dataColumns,
viewIDs
);
这个item view是如何设置的呢,我们看一下它的layout文件\sdk\platforms\android-19\data\res\layout\simple_list_item_activated_1.xml:
再看一下它用的背景图像是
android:background="?android:attr/activatedBackgroundIndicator"
这个style来自于系统文件\sdk\platforms\android-19\data\res\layout\theme.xml:
- @drawable/activated_background
这个drawable是什么呢,\sdk\platforms\android-19\data\res\drawable\activated_background.xml:
哦,原来在其他状态下,这个是透明图像,在activited状态,也就是listview 设置item view的时候用的状态,就显示为
list_selector_background_selected
这个图像如下:
如果你设置了对listview的item的check或者select而UI上没有效果,请首先参考上面的步骤是否正确。^_^!