Skip to content Skip to sidebar Skip to footer

Within A Listview, Why Do I Keep Getting The Value Of The First Row Instead Of The Selected Row?

In my android app I have the following code: public void goToCaptureBonus (View View) { String tappedBonus = ((TextView) findViewById(R.id.bonusListCode)).getText().toStrin

Solution 1:

The documentation of findViewById() says

Finds the first descendant view with the given ID, ...

Is it possible that you are using findViewById() from the context of the activity or the the general list view and not of the selected (tapped on) view?

If the view parameter of your function is the tapped on view, you should probably do:

view.findViewById(R.id.bonusListCode)

instead of just

findViewById(R.id.bonusListCode)

Solution 2:

In case of ListView you should use OnItemClickListener. Here is an example how to do this.

listView.setOnItemClickListener(newAdapterView.OnItemClickListener() {
    @OverridepublicvoidonItemClick(AdapterView<?> parent, View view, int position, long id) {
        //use the position variable to get the list item from the listStringselection= itemsArray[position]; // this will give the selected item 
    }
});

Now whenever an item on your ListView is tapped, the method onItemClick() is called. And here you can get the selection.

Post a Comment for "Within A Listview, Why Do I Keep Getting The Value Of The First Row Instead Of The Selected Row?"