我已经从SQLite数据库创建了一个ListView,但我仍然坚持如何为每个ListView项添加一个侦听器,这样当单击一个项时,我可以显示另一个页面,其中包含有关该项的更多信息。数据库只是一个样本。任何帮助将不胜感激。
public class Database extends ListActivity {
private final String SAMPLE_DB_NAME = "myFriendsDb";
//private final String SAMPLE_TABLE_NAME = "friends";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase db = null;
try {
db = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS people" +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
db.execSQL("INSERT INTO people" +
" Values ('Jones','Bob','UK',30);");
db.execSQL("INSERT INTO people" +
" Values ('Smith','John','UK',40);");
db.execSQL("INSERT INTO people" +
" Values ('Thompson','James','UK',50);");
Cursor c = db.rawQuery("SELECT FirstName, LastName FROM people", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
String lastName = c.getString(c.getColumnIndex("LastName"));
results.add("" + firstName + " " + lastName);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (db != null)
db.execSQL("DELETE FROM people");
db.close();
}
}
}
答案 0 :(得分:1)
有很多方法可以解决您的问题。一种可能的解决方案是:您只需在ListActivity中实现受保护的方法onListItemClick(ListView l,View v,int position,long id)。
public class Database extends ListActivity {
//YOUR CODE ABOVE HERE...
public static final String SHOWITEMINTENT_EXTRA_FETCHROWID = "fetchRow";
public static final int ACTIVITY_SHOWITEM = 0; /*Intent request user index*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
/*
position variable holds the position of item you clicked...
do your stuff here. If you want to send to another page, say another activity
that shows your stuff, you can always use an intent
example:
*/
Intent tmpIntent = new Intent(this, YourActivityForShowingItem.class);
tmpIntent.putExtra(SHOWITEMINTENT_EXTRA_FETCHROWID, position);
startActivityForResult(tmpIntent, ACTIVITY_SHOWITEM);
}
}
或者,您可以使用getListView()访问listActivity的ListView,并像使用常规ListView对象一样调用侦听器或上下文菜单的setter。例如,这个函数使用这种方法设置一个监听器:
private void setMyListListener(){
getListView().setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id){
/*same fake code as above for calling another activity using an intent:*/
Intent tmpIntent = new Intent(this, YourActivityForShowingItem.class);
tmpIntent.putExtra(SHOWITEMINTENT_EXTRA_FETCHROWID, position);
startActivityForResult(tmpIntent, ACTIVITY_SHOWITEM);
}
});
}
如果您希望在整个活动期间以相同的方式配置点击监听器,则此函数可由您的onCreate(...)函数调用。