Search code examples
androidlistviewonitemclick

when listview's item is click,how to make its view color to be red, others is black?


please look at the picture.

enter image description here this is listview, its item is a textview, I want to result is that when I click the item ,its textview's color turn to red,and all of others have no selected is black.

listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView one = (TextView) view.findViewById(R.id.item);
            one.setTextColor(Color.parseColor("#bb0e0e"));
        }
    });

I try like that, but it will when you click the item ,all of you click item will turn to be red. how can I do for my want?


Solution

  • define a global int variable

    int tempLocation;
    
    listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
       {
           tempLocation = position
          // adapter notify dataset change
          adapter.notifyDatasetChanged()
        }
    });
    

    And override the getView method of your adapter:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View view = View.inflate(context, R.layout.item_list, null);
    
        if (position == tempLocation) {
            // set your color
        }
    
        return view;
    }