我有ListView
,其中包含数据库中的项目。
我的适配器是:
Cursor cur = myDb.getCategories();
// Closing the cursor
// DEPRECATED!!
startManagingCursor(cur);
// Set up mapping from cursor to view fields
String[] fromFieldNames = new String[] { DBAdapter.KEY_ITEM_CAT };
int[] toViewIDs = new int[] { R.id.tvItemCat };
// Create adapter to map columns of DB to elements on UI
myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.category_layout, // Raw layout template
cur, // Cursor (set of DB records)
fromFieldNames, // DB column names
toViewIDs // views ID to putt in list view
);
// Set the adapter for list view
LVCat.setAdapter(myCursorAdapter);
getCategories():
Cursor c = db.rawQuery("SELECT DISTINCT " + KEY_ITEM_CAT + " as " + KEY_ITEM_ID
+ ", " + KEY_ITEM_CAT + " FROM " + ITEMS_TABLE_NAME, null);
if (c != null) {
c.moveToFirst();
}
return c;
我希望当我点击某个项目时,我应该获得项目名称。 我搜索了一下,发现了这段代码:
public void onCatClick(){
LVCat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
String category = LVCat.getItemAtPosition(position).toString();
// String category = parent.getItemAtPosition(position).toString(); --> This also I've tried, but the same result
System.out.println("Cat: " + category);
}
});
}
对于其他人来说,这是有效的。但我没有得到项目名称我得到这样的东西:
System.out(23858): Cat: android.database.sqlite.SQLiteCursor@4197f3a0
那么我该如何获得所选的项目名称?
答案 0 :(得分:1)
在onItemClickListener中使用parent.getItemAtPosition(position).toString()
来获取项目。
或使用它
TextView tv = (TextView) v.findViewById(R.id.tvItemCat);
String value = tv.getText().toString();