在Android中如何将ListAdapter值传递给onItemClick?

时间:2012-09-25 20:11:29

标签: android listview

我的应用程序上有一个正常运行的搜索界面。现在,我正在尝试使每个搜索结果列表项都可单击并显示在新活动中。我可以点击它们,但我无法弄清楚如何将ListAdapter值(记录)传递给onItemClick方法。

到目前为止,这是我的代码:

private void showResults(String query) {
    Cursor cursor = DBHelper.searchDB(query);
    startManagingCursor(cursor);
    String[] searchFrom = new String[] { DBAdapter.KEY_MAKE,
            DBAdapter.KEY_YEAR, DBAdapter.KEY_MAKE,
            DBAdapter.KEY_MODEL };
    int[] displayHere = new int[] { R.id.rDateTV, R.id.rYearTV,
            R.id.rMakeTV, R.id.rModelTV };

    final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
            R.layout.record_2, cursor, searchFrom, displayHere);

    setListAdapter(records);
    DBHelper.close();

    // --- Click on list item ---


    ListView clickList = getListView(); 
    clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
        @Override 
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)        {
            //--- here's the problem: how do I pass the ListAdapter values into onItemClick. the below doesn't like .getText()
            String sYear = (view.findViewById(R.id.rYearTV)).getText().toString();
            String sMake = (view.findViewById(R.id.rMakeTV)).getText().toString();
            String sModel = (view.findViewById(R.id.rModelTV)).getText().toString();

            // -- then pass these strings to an intent to launch a new activity




        } 
    });


    // --- END click on list item ----

}

有什么想法吗?我是这里的新手,所以如果你能告诉我代码,那就是AWSOME!

1 个答案:

答案 0 :(得分:2)

OnItemClickListener.onItemClick致电parent.getItemAtPosition(position)。该方法返回设置为给定位置的光标。然后从该游标中获取数据。不要在OnItemClickListener.onItemClick内关闭光标。

例如:

ListView clickList = getListView(); 
    clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
        @Override 
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)        {
            Cursor c = (Cursor)parent.getItemAtPosition(position)
            String sMake = c.getString(c.getColumnIndexOrThrow(DBAdapter.KEY_MAKE));//get data from cursor

           ...
        } 
    });