这是我的代码:
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
View vie = (View)parent.getParent();
TextView tv = (TextView) vie.findViewById(R.id.tv_id);
String genus = (String) tv.getText();
Toast.makeText(getBaseContext(), genus+"--"+id, Toast.LENGTH_SHORT).show();
}
});
return adapter;
}
每次它为每个项目返回相同的值。这是我的清单项目:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tv_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:textStyle="bold" />
<ImageView
android:id="@+id/iv_flag"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_below="@id/tv_country"
android:layout_centerVertical="true"
android:padding="5dp"
/>
<TextView
android:id="@+id/tv_country_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/iv_flag"
android:layout_below="@id/tv_country" />
<TextView
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_country_details"
/>
</RelativeLayout>
这是我的查看文件。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/lv_countries"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".NearbyGymList" />
<Button android:id="@+id/btnNoResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lv_countries"
android:text="No More Results"/>
</RelativeLayout>
如何解决这个问题?
最佳答案
您没有添加对其他TextView的引用。这样做:
删除此行
View vie = (View)parent.getParent();
因此您的代码将变为:
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView tv1 = (TextView) view.findViewById(R.id.tv_id);
TextView tv2 = (TextView) view.findViewById(R.id.tv_country_details);
String genus = (String) tv1.getText().toString();
String genus2 = (String) tv2.getText().toString();
Toast.makeText(getBaseContext(),genus+"--"+id+" "+genus2 , Toast.LENGTH_SHORT).show();
}
});
return adapter;
}