Psypher Psypher - 1 month ago 18
Android Question

Get all views in listview in setOnItemClickListener

I am using below code to setcolor of a selected item of a listview. The rule is only one should be colored. But with below code if I select 2 views both get colored. Can you please help me get all other views in the listview so that when I click on certain view all other views i set to different color and the selected view i set a different color(Green in this case).
Please let me know if any other solution?

enter image description here

lv = (ListView) view.findViewById(R.id.listf);
lv.setAdapter(text![enter image description here][1]Adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView v = (TextView) view.findViewById(R.id.template_text);
view.setBackgroundColor(Color.GREEN);
}
});

Answer

I resolved the problem using the below: I put a loop where only the selected list item is set in RED whereas all others were set in Green, in this way only only one list item will be colored on selected.

lv = (ListView) view.findViewById(R.id.listf);
lv.setAdapter(Adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    for (int i = 0; i < 3; i++) 
    {
       if (position == i) 
       {
           parent.getChildAt(i).setBackgroundColor(Color.RED);
       } 
       else 
       {
          parent.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.Dark_Green);
       }
    }
    TextView v = (TextView) view.findViewById(R.id.template_text);
    view.setBackgroundColor(Color.GREEN);
  }
});
Comments