1

I have i listview with 24 text views in it(each one of them present one hour of the day). What i am trying to do is to change background color of the item that i clicked.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                View v;
                v = parent.getChildAt(i);
                v.setBackgroundColor(Color.GREEN);

        }
    });

The problem is that when i click on a specific item not only bg color of one item is changed but also some other items change their colors.

i Know that

getChildAt()

does not always get the same fixed item. I want to know how that should be done so that only the item that is clicked change bg color.

EDIT: Thats the whole fragment class

public class GamesFragment extends Fragment  {
    //TopRatedFragment tf = new TopRatedFragment();

    List list = new ArrayList<Date>();
    public ArrayAdapter<String> adapter;
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    View v;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_games, container, false);
        final ListView listView = (ListView) rootView.findViewById(R.id.listView);

        for(int i = 0;i<24;i++){

            String date = Integer.toString(i) +":00";

            try{
            Date num = sdf.parse(date);
            SimpleDateFormat time = new SimpleDateFormat("HH:mm");

            list.add(time.format(num));
            }catch(ParseException e){
                e.printStackTrace();
            }

        }
        adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.layout1,R.id.textView,list);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                View v;
                v = parent.getChildAt(i);
                v.setBackgroundColor(Color.GREEN);

            }
        });



        listView.setAdapter(adapter);
        return rootView;
    }


}
  • That's due to getView, which get call multi time other item background changes. You need to make custom adapter and you can change background color from getView. Even though you have to store background color and set accordingly in list with respect to position. – Chitrang Nov 02 '14 at 19:11
  • As Chitrang said, you need to create a custom array adapter. – Jickson Nov 02 '14 at 19:40
  • If you don't want to create custom adapter, use this solution [Android: Access child views from a ListView](http://stackoverflow.com/a/17345134) – Wildroid Nov 02 '14 at 19:50

0 Answers0