onListItemClick,获取值需要什么语句?

时间:2011-04-12 12:34:37

标签: android android-listview

我可以添加到数据库并列表作为列表视图。 当我使用onListItemClick单击列表项时,我会做什么声明 需要获得价值吗?

提前致谢。

public class Main extends ListActivity {
private static String[] FROM = { _ID, DESCRIPTION, UN };
private static String ORDER_BY = DESCRIPTION + " ASC";
private static int[] TO = {R.id.itemrowid, R.id.itemdescription, R.id.itemun };
private EventsData events;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    events = new EventsData(this);
    try {
        Cursor cursor = getEvents();
        showEvents(cursor);
     } finally {
        events.close();
     }

**public void onListItemClick(ListView parent, View v, int position, long id) {
    // What statement to put here to get the value of _ID,DESCRIPTION, UN
    // selected**?
}

private Cursor getEvents() {
    // Perform a managed query. The Activity will handle closing
    // and re-querying the cursor when needed.
    SQLiteDatabase db = events.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
            null, ORDER_BY);
    startManagingCursor(cursor);
    return cursor;
}

private void showEvents(Cursor cursor) {
    // Set up data binding
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.item, cursor, FROM, TO);
    setListAdapter(adapter);
}

2 个答案:

答案 0 :(得分:8)

首先,您需要在点击位置获取项目:

Cursor cursor = getListAdapter().getItem(position);

然后你可以从这个光标获取数据(我不知道你使用什么类型,所以只是例如intString):

int id = cursor.getInt(cursor.getColumnIndex(_ID));
String description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));

有关Cursor的可用方法,请参阅documentation

答案 1 :(得分:0)

添加到sergey的答案中,您还可以直接查看单击的View,并使用findViewById()查找组件,因此,您需要的值。

这只是替代方法,谢尔盖更少'补丁'