How to Change Color of Listview Items on Focus and on Click

Change colour of listview item when clicked

If you just want to change the color once:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

view.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

}

});

You can toggle the change of a list view item with something like this:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

LoadListerListViewObject currentObject = loadListerListViewObjectArrayList.get(position);
//If the object is inactive...
if (!currentObject.getIsActivated()) {
//Set the object as active and change the color to green
loadListerListViewObjectArrayList.set(position, new LoadListerListViewObject(currentObject.getDate(), currentObject.getTagNumber() true));
view.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
//If the object is active...
} else {
//Set the object as active and change the color to grey
loadListerListViewObjectArrayList.set(position, new LoadListerListViewObject(currentObject.getDate(), currentObject.getTagNumber(), false));
view.setBackgroundColor(getResources().getColor(R.color.colorGreyForButton));
}

}

});

This uses a property of the associated list view object to check if the item's been selected or not, then changes colors based on this. I'd imagine you'd want to "un-change" the color, too. Something like this is likely what you'd need.

Change background color of selected item on a ListView

You can keep track the position of the current selected element:

    OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
mSelectedItem = position;
mAdapter.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 == mSelectedItem) {
// set your color
}

return view;
}

For me it did the trick.

Android : ListVIew : change background onClick

The problem is that your adapter for list is reusing the views which are moved out of screen.

The solution is to set default color in adapter for other views

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

if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) convertView.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
= inflater.inflate(
R.layout.your_list_item, null);

}
if(postion!=SelectedPosition)
{
convertView.setBackgroundColor(default Color);
}
else
{
convertView.setBackgroundColor(Color.argb(125,75,236,90));
}

return convertView;

}


Related Topics



Leave a reply



Submit