[英]Access a database value on a ListView
我有一個這樣的網頁數據庫:
import android.provider.BaseColumns;
public interface ThreadDatabase extends BaseColumns {
String TABLE_NAME = "Threads";
String TITLE = "Title";
String DESCRIPTION = "Description";
String URL = "Url";
String[] COLUMNS = new String[] { _ID, TITLE, DESCRIPTION, URL };
}
在我的活動中,還有一個帶有SimpleCursorAdapter的Listview,它在每一行中顯示Title和Descripton。
Cursor c = dbhelper.getDatabase();
setListAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, c, new String[] {
ThreadDatabase.TITLE, ThreadDatabase.DESCRIPTION },
new int[] { android.R.id.text1, android.R.id.text2, })
如何重新定義onListItemClick方法,以便在單擊該項目時打開正確的URL?
protected void onListItemClick(ListView l, View v, int position, long id) {
???Missing part???
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
您需要對SimpleCursorAdapter的引用,因此將其初始化為字段。
假設您有一個字段mAdapter,則可以這樣獲得光標:
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
希望能有所幫助。
我假設您的活動擴展了ListActivity。 如果是這樣,在onListItemClick()中,您需要做的是:
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor item = (Cursor)getListAdapter().getItem(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.