SimpleCursorAdapter 綁定 Cursor,點擊項目需獲取 gotoURL 字段傳遞給下一個 Activity。
// Adapter 中暴露靜態字段 (極差實踐)
public static String gotoURL; // 多線程不安全、數據錯亂、記憶體洩漏
lv.setOnItemClickListener((parent, view, position, id) -> {
// 關鍵:移動 Cursor 到點擊位置
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
if (cursor != null) {
int urlIndex = cursor.getColumnIndex("gotoURL");
String url = cursor.getString(urlIndex);
Intent intent = new Intent(List_AC.this, DocView.class);
intent.putExtra("url", url);
startActivity(intent);
}
});
注意:parent.getItemAtPosition(position) 返回的是 Cursor,需先 moveToPosition (SimpleCursorAdapter 內部已處理)。
// 1. 定義數據模型
class AdvisoryItem {
String label, title, description, gotoURL;
}
// 2. 查詢數據庫轉為 List
List items = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM AC_list ORDER BY label ASC", null);
while (cursor.moveToNext()) {
AdvisoryItem item = new AdvisoryItem();
item.label = cursor.getString(cursor.getColumnIndex("label"));
item.title = cursor.getString(cursor.getColumnIndex("title"));
item.description = cursor.getString(cursor.getColumnIndex("description"));
item.gotoURL = cursor.getString(cursor.getColumnIndex("gotoURL"));
items.add(item);
}
cursor.close();
// 3. 自定義 Adapter
class AdvisoryAdapter extends BaseAdapter {
private List items;
// ... getView 中綁定 items.get(position)
@Override
public AdvisoryItem getItem(int position) {
return items.get(position);
}
}
// 4. 點擊獲取模型對象
lv.setOnItemClickListener((parent, view, position, id) -> {
AdvisoryItem item = (AdvisoryItem) parent.getItemAtPosition(position);
Intent intent = new Intent(List_AC.this, DocView.class);
intent.putExtra("url", item.gotoURL);
startActivity(intent);
});
// Adapter
class AdvisoryAdapter extends ListAdapter
extends ListAdapter(DIFF_CALLBACK) {
static final DiffUtil.ItemCallback DIFF_CALLBACK =
new DiffUtil.ItemCallback() {
@Override boolean areItemsTheSame(AdvisoryItem old, AdvisoryItem n) {
return old.gotoURL.equals(n.gotoURL); // 唯一標識
}
@Override boolean areContentsTheSame(AdvisoryItem old, AdvisoryItem n) {
return old.equals(n);
}
};
// ViewHolder 綁定...
// Activity 中點擊可用 OnItemTouchListener 或 ViewHolder 內部點擊
}
adapter.getItem(position) 或 parent.getItemAtPosition(position)