【问题标题】:How to reference Item in ListView when there are more than 1 items?当有超过 1 个项目时,如何在 ListView 中引用项目?
【发布时间】:2014-12-09 18:08:05
【问题描述】:

大家好,这是我的代码:

private void populateListView() {

    Cursor cursor = mydb.getAllEvents();

    String[] fromFieldNames = new String[]
            {DBHelper.EVENTS_COLUMN_NAME,DBHelper.EVENTS_COLUMN_CATEGORY};

    int[] toViewIDs = new int[]
            {R.id.event_name, R.id.cat_name};

    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(this,R.layout.item_layout,cursor,fromFieldNames,toViewIDs,0);
    final ListView myList = (ListView) findViewById(R.id.listView1);

    myList.setAdapter(myCursorAdapter);

    myList.setOnClickListener(new AdapterView.OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selected = myList.getItemAtPosition(position);
        }
    });`

正如您所见,该位置有多个项目,那么如何分别引用每个项目?例如,我只想引用事件的名称。

【问题讨论】:

  • 我认为`该位置有多个项目`的说法并不准确!每个位置将包含光标中的 1 个项目

标签: android sqlite


【解决方案1】:

myList.getItemAtPosition(position) 为您获取代表该位置行的“对象”。简单地说,这是由您的 CursorAdapter 定义的。这实际上是一个 Cursor 对象,应按如下方式进行转换:

Cursor myCursor = (Cursor) myList.getItemAtPosition(position);

然后您必须从光标中的正确位置获取字符串(应该按照您放入适配器的任何顺序):

String myDesiredString = myCursor.getString(cursorPos);

其中 cursorPos 是一个整数,表示您希望获得的位置。

有关更多信息,这里有一个很好的类似问题: getItemAtPosition() How to get readable data....

附带说明一下,我个人更喜欢使用我自己的扩展 BaseAdapter 的适配器,这样我就可以更好地控制数据,甚至可以让适配器本身返回数据[例如定义像 public String getEventName(int position) 这样的方法]。但是,对于这种情况,最简单的解决方案就是我上面描述的。

【讨论】:

    【解决方案2】:

    拥有cursor 对象允许您使用positionmoveToPosition() 获取项目

    试试这个:

    cursor.moveToPosition(position);
    cursor.getString(1); // OR
    cursor.getInt(1);// OR whatever you need.
    

    更多信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多