基本上我正在做的是通过 ListView 向用户提供术语列表。这些术语在 strings.xml 中定义为字符串:
<item name="Bahrain testing">Bahrain</item>
<item name="Bangladesh testing">Bangladesh</item>
<item name="Barbados testing">Barbados</item>
<item name="Belarus testing">Belarus</item>
<item name="Belgium testing">Belgium</item>
<item name="Belize testing">Belize</item>
<item name="Benin testing">Benin</item>
我在myActivity.java中处理ListView:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seoguide);
String[] countries = getResources().getStringArray(R.array.seoterm_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.seoguide, countries));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
这就是我有点不知所措的地方,我尝试通过获取属性通过项目名称来定义它,但这似乎不起作用。
我怀疑问题可能是由于没有在 seoguide.xml 中定义可点击
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="22sp" >
</TextView>
但是我还没有看到其他教程的XML中定义了clickable。
我希望发生的是,当用户选择巴林时,Toast 会弹出一条消息,内容如下:“巴哈林是波斯湾西海岸附近的一个小岛国。”
预先感谢您的帮助!
编辑 将 myview.xml 更改为 seoguide.xml - 反射(reflect)相同的信息
最佳答案
Use this..
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String str_item = lv.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), str_item,
Toast.LENGTH_SHORT).show();
}
}
关于java - 在 ListView 中选择项目,然后使用 toast 在单击时显示自定义消息(针对每个项目),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9156931/