2009-11-10 116 views
2

我有我从我的Sqlite数据库检索到的项目列表... 我想为每个项目设置一个Click事件。我如何根据点击的项目自定义此事件? 具有描述性......我是初学者。ListView Click事件

这是我用我的列表中填写数据的方法:在ListView

private void fillData() { 
    db = new DBAdapter(this); 
    db.open(); 
    ArrayList db_results = new ArrayList(); 
    //All Category 
    //Cursor cursor = db.getAllTitles(); 

    //Single Category 
    Cursor cursor = db.getTitle(1); 
    if (cursor.moveToFirst()) 
    { 
     do {   
      db_results.add(cursor.getString(4)); 
     } while (cursor.moveToNext()); 
    } 
    cursor.close(); 

    this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, db_results)); 
} 
+0

当你点击不同的列表项目时,你想要什么不同的行为?这个问题让我感到困惑。 – I82Much

回答

4

呼叫setOnItemClickListener()。您提供的AdapterView.OnItemClickListener听众将获得位置(基于0的索引)和ID(如果您使用的是CursorAdapter,则应该如此,而不是将Cursor转换为ArrayList),以便您知道哪个项目被点击。

+0

嗨马克,我期待做同样的事情。从网络上看,你所提出的是实现它的方式,但我无法在任何地方找到一个体面的代码示例。 您的书中是否有一本书?如果是这样,页码请:) – Tom

+0

本书中的许多ListView示例使用ListActivity并重写onListItemClick(),其中(IIRC)给出了相同的参数。例如http://github.com/commonsguy/cw-android/tree/master/Selection/List/。 – CommonsWare

+0

再次感谢Mark,看起来正是我们需要的:) – Tom