Reputation: 351
I have a class that extends Fragment
. I have a ListView
. When I click on an item, it return always the same item.
Here the row.xml of the ListView adapter.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:id="@+id/IdItem"/>
</LinearLayout>
And here the event:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
myTextView = (TextView)getActivity().findViewById(R.id.IdItem);
String IdItem = myTextView.getText().toString();
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra("IdItem", IdItem);
startActivity(intent);
}
});
It always returns the same IdItem, and not the choosen one.
Upvotes: 1
Views: 539
Reputation: 1196
Change this:
myTextView = (TextView)getActivity().findViewById(R.id.IdItem);
for this:
myTextView = view.findViewById(R.id.IdItem);
The rows objects of a ListView are reused in order to save memory, so you need to use the View object being sent in the onItemClick method of the ListView. This View object represents the actual clicked row inside the ListView with current child Views and values.
Upvotes: 1