我的ListView是從我的數據庫中拉出的食譜列表。我正在嘗試獲取ListView中單擊項目的文本。 ListView通過數據庫調用和cursoradapter進行填充。我想使用所選項目的文本在另一個活動中進行另一個數據庫調用。下面是代碼塊從點擊列表視圖項目獲取文本
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
final String text = ((TextView)v).getText().toString();
recipeid = myDBAdapter.getRecipeID(text);
Intent intent = new Intent(ListAllRecipes.this, DisplayRecipe.class);
intent.putExtra("recipeid", recipeid);
startActivity(intent);
}
});
當我運行我的代碼,我得到
04-22 14:08:37.022: E/AndroidRuntime(25206): FATAL EXCEPTION: main
04-22 14:08:37.022: E/AndroidRuntime(25206): java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
04-22 14:08:37.022: E/AndroidRuntime(25206): at com.example.ketorecipes.ListAllRecipes$1.onItemClick(ListAllRecipes.java:47)
當我點擊在ListView的項目。
這裏是一個大塊的活動:
public class ListAllRecipes extends Activity{
private DBAdapter myDBAdapter;
private ListView listView;
private int recipeid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_all);
myDBAdapter = new DBAdapter(this);
myDBAdapter.openToRead();
Cursor c = myDBAdapter.getValues();
listView = (ListView)findViewById(R.id.listView1);
String[] from = new String[] {"_id"};
int[] to = new int[] {R.id.name_entry};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.list_entry, c, from, to);
listView.setAdapter(cursorAdapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
final String text = ((TextView)v).getText().toString();
recipeid = myDBAdapter.getRecipeID(text);
Intent intent = new Intent(ListAllRecipes.this, DisplayRecipe.class);
intent.putExtra("recipeid", recipeid);
startActivity(intent);
}
});
}
}
_id相反鑄造底層佈局'的名稱'TextView''你應該使用''v.findViewById(your_textview_id)''檢索文本。 – harism 2013-04-22 19:20:39
謝謝你的迴應。我對Android還是很陌生,我也不是一個非常強大的程序員。你能詳細說明一下嗎? – Michael 2013-04-22 19:32:48
我假設你正在使用基於RelativeLayout的自定義佈局來填充ListView?現在點擊ListView將會給你這個佈局主視圖作爲''View''參數。但是你可以通過使用View.findViewById(resource_id_assigned_for_TextView)來檢索底層的''TextView''。 – harism 2013-04-22 19:37:52