ListActivity.getSelectedItemId()取不到值的问题
今天研究动态菜单(sdk中的记事本例子google example:notepad)时发现 getSelectItemId() 无论如何拿到的都是Long.MIN_VALUE即-9223372036854775808
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
final boolean haveItems = getListAdapter().getCount() > 0;
// If there are any notes in the list (which implies that one of
// them is selected), then we need to generate the actions that
// can be performed on the current selection. This will be a combination
// of our own specific actions along with any extensions that can be
// found.
if (haveItems) {
// This is the selected item.
Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId());
网上多方查证无果,很多人有同样问题,有解决方法但不知道问题原因。最后终于在android issue上找到解释 http://code.google.com/p/android/issues/detail?id=259&can=1&q=getSelectedItemId&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars
原文如下:
Hi,
Is this a click performed in touch mode or with the keys? If it's in touch mode, then
this is normal. The concept of focus or selection does not exist in touch mode.
Instead, you should rely on the value passed to you in onListItemClick().
大意是说触屏模式下该方法不可用,因为触屏模式下没有foucs或selection的概念,你必须在onListItenClick()回调中获得选中id。
想想确实如此,只有键盘手机才会有上下键来选择item,由于我的测试机是nexus s,无方向键,才会纠结这么久....- -0 。用模拟器debug了下,结果正确。好了,现在你应该明白notepad例子中Notelist那两个动态菜单是为键盘机准备的了吧。