I'm filling a listview, here is the code :
ArrayAdapter<CharSequence> listAdapter1;
ListView toc;
toc=(ListView)findViewById(R.id.listView1);
listAdapter1=ArrayAdapter.createFromResource(Glossary.this,R.array.arabicalphabet,R.layout.glossarysimplerow);
toc.setAdapter(listAdapter1);
I'm setting a list selector in the xml file, when clicking on any item in the list its color will change to blue to show that it is selected. The problem is, when I scroll the listview the selection will change, for example if I have a list filled from A to Z, If I select the letter "B" and I scroll many times, I get the letter "M" selected... Any help please
In Android the children of AdapterView like ListView have caching enabled, so when user scrolls, the items off the screen are off the memory, getView() is called for the items that are to be shown on the view after scrolling.
The View that is passed in the getView() method is reused and has properties of the previously visible views in the ListView. This improves the performance of the ListView but makes it necessary to check for all the possible conditions and reset all the properties of the view received in the getView().
Now the generic ArrayAdapter that you used has no implementation of changing colors on click and it doesn't have any way to keep a record of the view already clicked. So on scrolling the results are unexpected.
You may implement your own Adapter class as shown below and it will solve your issue:
public class MyAdapter extends ArrayAdapter<String> {
Context context;
List<String> lstStrings;
List<Boolean> isClicked;
public MyAdapter (Context context, int resource, List<String> lstStrings) {
super(context, resource, lstStrings);
this.context = context;
lstStrings = lstStrings;
isClicked = new ArrayList<>(Arrays.asList(new Boolean[lstStrings.length]));
Collections.fill(isClicked, new Boolean(false));
}
@Override
public int getCount() {
return lstStrings.size();
}
@Override
public String getItem(int position) {
return lstStrings.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = LayoutInflater.from( context).inflate(R.layout.list_item, null);
TextView txtTheText = (TextView) convertView.findViewById(R.id.txtTheText);
txtTheText .setText(lstStrings.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isClicked.set(!isClicked.get(position));
}
});
if (isClicked.get(position))
convertView.setBackgroundColor(Color.argb(255, 255, 0, 0));
else
convertView.setBackgroundColor(Color.argb(255, 0, 0, 255));
return convertView;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With