Search code examples
androidlistviewonitemclicklistener

How to Show/Hide a TextView from ListView


I have a ListView with items who have the same view to display some data, I have an OnItemClickListener, when I click on one item, it displays a TextView (previously hidden) as an expandable text.

The problem


If I click the first item and I start to scroll down, the others items (randomly) show the TextView expanded, I only want to show the current TextView of the item who I have clicked.

Can anyone give me a clue to do it correctly?

Thanks so much

My code:

@Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
           TextView expandedText = (TextView)view.findViewById(R.id.txtExpanded)
           if(expandedText.getVisibility()==View.VISIBLE){
              expandedText.setVisibility(View.GONE)
           }else{
              expandedText.setVisibility(View.VISIBLE)}
        }

Solution

  • Without seeing your actual adapter, I guess that happens because you are using viewholders. Since viewholders recycle widgets and reset data, each time a holder used to display a clicked cell gets recycled, displays the new data with the "clicked" logic applied. So, "reset" the widgets to the base state and keep track of which "data" was already clicked, ideally inside the data object itself. It would be good to create a viewgroup to handle all the widgets and the logic for showing/hide the field instead of setting them into the adapter.