Android:列表视图所选项目-1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2433952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:50:34  来源:igfitidea点击:

Android: List View Selected item -1

android

提问by Sosi

Im getting a -1 value when i try to get the selected item position on my listview that is already populated.

当我尝试在已填充的列表视图上获取所选项目位置时,我获得了 -1 值。

list.setOnItemClickListener
(
   new AdapterView.OnItemClickListener() 
   {
       public void onItemClick(AdapterView adapterView, View view,int arg2, long arg3)
       {
          int selectedPosition = adapterView.getSelectedItemPosition();
          ShowAlert(String.valueOf(selectedPosition));
       }
   }
);

To fill my list view i use the following code:

要填充我的列表视图,我使用以下代码:

SimpleAdapter mSchedule = new SimpleAdapter(
          this, 
          mylist, 
          R.layout.listviewtest,
          new String[] {"test1", "test2", "test3"}, 
          new int[] {R.id.TextView_websitename, R.id.TextView_keywords, R.id.TextView_backlink});

Any idea?

任何的想法?

Thanks in advance.

提前致谢。

Best Regards.

此致。

Jose.

何塞。

回答by CommonsWare

That means there is no row selected. The documentationstates that getSelectedItemPosition()returns:

这意味着没有选择行。该文件指出getSelectedItemPosition()的回报:

int Position (starting at 0), or INVALID_POSITION if there is nothing selected.

int 位置(从 0 开始),如果没有选择任何内容,则为 INVALID_POSITION。

And INVALID_POSITIONis -1.

并且INVALID_POSITION-1

Note that you are calling getSelectedItemPosition()from an OnClickListener. Click and selection are not necessarily related. Selection comes from using the D-pad or trackball to navigate the list contents. If the user taps on the screen (or clicks in the emulator), there will be no selection anymore, but there will still be a click event.

请注意,您是getSelectedItemPosition()OnClickListener. 单击和选择不一定相关。选择来自使用方向键或轨迹球来导航列表内容。如果用户点击屏幕(或在模拟器中点击),将不再有选择,但仍然会有点击事件。

The arg2value you show is the position of the clicked-upon item in the list.

arg2您显示的值是列表中单击项目的位置。