当我在列表视图中选择项目时,我想获得所选项目的值。
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = getText(position).toString();
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
在这个代码String data = getText(position).toString()
中,我得到了这个错误:
字符串资源ID#0x0
此代码是添加列表视图
void DBadd() {
String name = addTxt1.getText().toString();
String info = addTxt2.getText().toString();
if (name.equals("") || info.equals("")) {
Toast.makeText(getApplicationContext(), "정보를 입력해 주세요", Toast.LENGTH_SHORT).show();
return;
} else {
db.execSQL("INSERT INTO tableName VALUES (null, '" + name + "', '" + info + "');");
Toast.makeText(getApplicationContext(), "추가 성공", Toast.LENGTH_SHORT).show();
addTxt1.setText(""); //입력시 EditText에 입력된값 지움
addTxt2.setText("");
cursor = db.rawQuery("SELECT * FROM tableName", null);
startManagingCursor(cursor); //엑티비티의 생명주기와 커서의 생명주기를 같게 한다.
adapter = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_1);
adapter2 = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_1);
while (cursor.moveToNext()) {
adapter.add(cursor.getString(1));
adapter2.add(cursor.getString(2));
}
listView.setAdapter(adapter);
listView2.setAdapter(adapter2);
}
}
如何获取所选项目的值?
试试这个,它对我有用:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = listView.getItemAtPosition(position).toString();
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
或者,只需使用.get(postion)
直接从adapter
获取字符串值,如下所示:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = adapter.get(position);
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
好运
我不确定我是否正确理解了你的问题,但让我猜一下想要的行为:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textViewOfTheClickedRaw = view.findViewById(android.R.id.text1);
String data = textViewOfTheClickedRaw.getText().toString();
Toast.makeText(Main2Activity.this, data, Toast.LENGTH_SHORT).show();
}
});
这就是如何从android.R.layout.simple_list_item_1
中获取TextView的值
但我真的不认为这是你的应用应该如何工作