简体   繁体   中英

How to change background color of only the clicked item in ListView in Android Studio?

Whenever a user presses on the listview, it changes its background color to red. However, when i press another item, the old item still retains the background color of red. How to edit it such that only the clicked item has the background color changed.

lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
        view.setSelected(true);
        view.setBackgroundColor(Color.RED);

        nameSelected = contactHolderArrayList.get(position).name;
        phoneSelected = contactHolderArrayList.get(position).phone;

        //Anything
    }
});

I just implemented a simple counter to keep track of prev and current position and it works! Please comment if anything is wrong. I initialized counter to 0 in oncreate and incremented each time list item is pressed and then included below code in onitemclicklistener

lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
            //view.setSelected(true);

            if(counter==0) {
                prevPosition = position;
            }
            else if (counter ==1) {
                currentPosition = position;
            }
            else {
                prevPosition = currentPosition;
                currentPosition = position;
            }
            lvContact.getChildAt(prevPosition).setBackgroundColor(Color.TRANSPARENT);
            view.setBackgroundColor(Color.RED);
            counter++;

you need to apply onTouchListener on view inside ListView adapter then need to set new Color on Down action and Old color on Up action

public View getView(int position, View convertView, ViewGroup parent)
{
         view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    // apply new color
                }
                if(event.getAction() == MotionEvent.ACTION_UP){
                    // apply old color
                }
                return false;
            }
        });
       return view;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM