简体   繁体   中英

ListView change background of selected item

I want to set the currently clicked item to a different colour which I have implemented as this.

@Override
public void onItemClick(StaggeredGridView parent, View view, int position,
        long id) {
    Toast.makeText(MainActivity.this, "Clicked Position "+position, Toast.LENGTH_LONG).show();
    Log.d("Clicked","Clicked Position "+position+" Content "+contentList.get(position));
    if(prevSelected !=null)
    {
        prevSelected.setBackgroundColor(getResources().getColor(android.R.color.white));

    }
    prevSelected = view;
    view.setBackgroundResource(R.drawable.list_pressed_holo_light);
    selectedPosition = position;
} 

Now the problem I am facing is that if this selected view is recycled in getView() all those views also have this same background. If I change their background then the background of this view also changes. Anyone has a solution to this.

If you set the required background also in getView() method everything will work fine ;) Just put in your getView(int position, View convertView, ViewGroup parent) method:

if (convertView != null){
    if (position == selectedPosition) {
        convertView.setBackgroundColor(getResources().getColor(android.R.color.white));
    } else {
        convertView.setBackgroundResource(R.drawable.list_pressed_holo_light);
    }
}

its so easy my friend go to this site and you will find your answer.

change the color of an item when clicked and even the color of the text inside the listview

This is the solution I've ended up with in my getView().

            if (convertView != null){
            // If the selected view is used somewhere else
            if (convertView.equals(prevSelected) && position != selectedPosition)
            {
                convertView.setBackgroundColor(getResources().getColor(android.R.color.white));
                Log.d("Yup", "Changing color");
                Log.d("Yup", position + "  " + selectedPosition);
            }
            // If the selected view is redrawn and the recycled view is not
            // the same view again
            else if (position == selectedPosition && !convertView.equals(prevSelected))
            {
                // Make all other views if any which were prev selected
                // white
                prevSelected.setBackgroundColor(getResources().getColor(android.R.color.white));
                prevSelected = convertView;
                convertView.setBackgroundResource(R.drawable.list_pressed_holo_light);
                Log.d("Yup", "Setting pressed color");
                Log.d("Yup", position + "  " + selectedPosition);
            }
            // The case where pos == selected pos and same view was used
            // again.Need to set it to that colour as it could have been
            // changed in the first condition
            else if(position == selectedPosition && convertView.equals(prevSelected))
            {
                prevSelected = convertView;
                convertView.setBackgroundResource(R.drawable.list_pressed_holo_light);
                Log.d("Yup!", "Setting that view colour");
                Log.d("Yup!", position + "  " + selectedPosition);
            }
            }

Try with a custom adapter this also helps you to have full control over your items and set a default item selected; listView XML and item XML have no special setup. Using getViewTypeCount() and selectedViewType is the key to avoid recycling your views.

public class ListAdapter extends ArrayAdapter<MyObj> {

private final int layoutInflater;
private Context context;
private  List<MyObj> items;
private int mSelectedItem = 0;
private int TAG_UNSELECTED = 0;
private int TAG_SELECTED = 1;

public ListAdapter(Context context, int resource, List<MyObj> items) {
    super(context, resource, items);
    this.context = context;
    this.layoutInflater = resource;
    this.items = items;
}

public void selectItem(int position) {
    mSelectedItem = position;
    notifyDataSetChanged();
}


@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public int getItemViewType(int position) {
    return position == mSelectedItem ? TAG_SELECTED : TAG_UNSELECTED;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(layoutInflater, null);
    }

    MyObj myObj = items.get(position);
    TextView textView = (TextView) v.findViewById(R.id.title);
    textView.setText(myObj.title);

    int type = getItemViewType(position);
    if(type == TAG_SELECTED) {
        v.setBackgroundColor(Color.parseColor("#1da7ff"));
        textView.setTextColor(Color.parseColor("#ffffff"));
    } else {
        v.setBackgroundColor(Color.parseColor("#f8f8f8"));
        textView.setTextColor(Color.parseColor("#474747"));
    }

    return v;
}

}

Then in your activity:

            ListView listView = (ListView) findViewById(R.id.list_view);
            ListAdapter adapter = new ListAdapter(mContext, R.layout.item_layout, list);
            listView.setAdapter(adapter);
            adapter.selectItem(0); // Default selected item

            // Get selected item and update its background
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    adapter.selectItem(position);
                }
            });

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