0

I am using a ListView with an ArrayAdapter, and I want to change the color of text inside of a TextView when the user clicks on it. This works fine except when one TextView changes color another one further down the list changes color too.

Does this have something to do with ArrayAdapter reusing views?

ArrayAdapter<String> adapter = new ArrayAdapter<> (thisContext, R.layout.textview_1, arrayList);
listView.setAdapter (adapter);

listView.setOnItemClickListener (new AdapterView.OnItemClickListener ()
{
    @Override
    public void onItemClick (AdapterView<?> parent, View view, int   position, long id)
    {
        TextView textToChange = (TextView) view;
        textToChange.setTextColor (Color.RED);
    }
});
Mode77
  • 729
  • 7
  • 25

1 Answers1

1

Does this have something to do with ArrayAdapter reusing views?

Yes.

You can solve this by overriding getView() when you create your ArrayAdapter, by doing something like this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(thisContext, R.layout.textview_1, arrayList) {

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // TODO
    }
};

How you actually go about solving it will depend on what behavior you want. It seems like your item views are TextViews really, so you could replace the TODO with something like this:

TextView tv = (TextView) super.getView(position, convertView, parent);
tv.setTextColor(Color.BLACK);
return tv;

That will make sure that any recycled view has black text, but it will also mean that if you click on a row (so it turns red), scroll that row out of view, and then scroll it back into view, it will go back to being black.

Perhaps you could update a variable that stores your last clicked position from within your OnItemClickListener, and then reference that in getView():

TextView tv = (TextView) super.getView(position, convertView, parent);
tv.setTextColor(position == lastClickedPosition ? Color.RED : Color.BLACK);
return tv;
Ben P.
  • 44,716
  • 5
  • 70
  • 96