Search code examples
androidandroid-listviewlistviewitemfindviewbyid

Android ListView FindViewById confusion


I had a Listview with the following Adapter

SimpleAdapter simpleAdapter
            = new SimpleAdapter(NewsListActivity.this,res,R.layout.newslist_adapter,new String[]{"title","description","link"},new int[]{R.id.title,R.id.description,R.id.url});    
            
            lView.setAdapter(simpleAdapter);

where lView is the ListView, and res is an HashMap.

In the ListView's onItemClick, I was able to get each View's Description TextView using the Code below

    @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                {
                    
                    View v1 = lView.getChildAt(position - lView.getFirstVisiblePosition());
                    
                    if(v1 != null){
                    TextView des = v1.findViewById(R.id.description);
                    Toast.makeText(getApplicationContext(),des.getText(),0).show();       // returns the Text at exact TextView Clicked
                    des.setBackgroundColor(R.color.red);   //Here is the PROBLEM, It changes the Background Color of TextView I clicked on, but it ALSO changes some other TextView's background color
                    }
            }

As I added in the Comments, The Toast message returns The exact Text in the TextView, but changing the background color also changes some other TextView in the ListView's color

I don't seem to Understand what I am doing wrong.

EDIT

I only posted the portion of the project , so as not mess up all the place with my source code.

It's an RSS feed reader project, but now I realize the problem is with all ListViews. Pleased kindly help with the link below

Android ListView getChild() not working properly


Solution

  • Ok, after months of confusion, pain of being self-taught and punishment of walking alone (no direct access to senior dev for help), I finally realized what I was missing.

    The problem arise from ListView re-using view as some sort of memory management techniques (for performance purposes) or so. That's why in my case whenever the background color of a ListView Element is changed and the View is being recycled it affect the background color of whichever item that uses the Recycled view.

    As for the fix, this this link should help