I have a ListView
of a custom object with a custom adapter. Clicking on an individual item of list starts a new activity for result that updates that item and then returns back to the list with a green tick image on the right side of the ListView
item which is a TextView
and I just use row.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.tick_green, 0)
However when I scroll down, I see another row with the same drawable. Scrolling back and forth just sets this drawable to different rows randomly. Most answers say that it's because the views are being recycled but what is the way to change one single row irrespective of whether it is visible or not when the other activity returns a result?
code from Activity with the list view -
private ItemAdapter adapter;
private ArrayList<Item> labels;
private ArrayList<Item> updatedItems;
private TextView label;
@Override
protected void onCreate(Bundle savedInstanceState) {
// initializations
updatedItems = new ArrayList<>();
adapter = new ItemAdapter(getBaseContext(), R.layout.label_list_item, labels);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
label = (TextView) listView.getChildAt(position - listView.getFirstVisiblePosition()).findViewById(R.id.text1);
Item item = adapter.getItem(position);
Intent myIntent = new Intent(ProviderPutawayActivity.this, PutawayScanLocationActivity.class);
myIntent.putExtra("ITEM", item);
ProviderPutawayActivity.this.startActivityForResult(myIntent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1) {
Item item = (Item) data.getSerializableExtra("ITEM");
label.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.tick_green, 0);
}
v.findViewById(r.id.text1)
and (TextView) listView.getChildAt(position - listView.getFirstVisiblePosition()).findViewById(R.id.text1)
as suggested here both have the same problem.
The ItemAdapter class -
public class ItemAdapter extends ArrayAdapter<Item> {
private View v;
public ItemAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
v = convertView;
TextView label;
if(v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.label_list_item, null);
}
Item item = getItem(position);
if(item != null) {
label = (TextView)v.findViewById(R.id.text1);
if(label != null) label.setText(String.valueOf(item.getLabel()));
}
return v;
}
}
How do I make sure I only update the row that was clicked?