I tried to implement the multiselection on Android ListView. I want to select/deselect more than one item and these items should keep highlighted or not. I don\'t want to us
this is a code example of what I use to create custom adapters. The first Function is used to call the custom adapter from within your main activity. ListAdapter is your custom Java file to be called.
List CustomAdapterList = new ArrayList();//List with items to send to the custom adapter
List items = new ArrayList();
private void populateCustomList()
{
ArrayAdapter Population= new CustomAdapter();
ListView list= (ListView)findViewById(R.id.listView);
list.setAdapter(Population);
}
private class CustomAdapter extends ArrayAdapter
{
public CustomAdapter (){super(Settings.this,R.layout.listadapter,CustomAdapterList);}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View itemView = convertView;
if (itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.listadapter, parent, false);
}
final ListAdapter Position = CustomAdapterList.get(position);
final TextView tv= (TextView)itemView.findViewById(R.id.tv);
tv.setText(Position.getText());
final RelativeLayout layout= (RelativeLayout)itemView.findViewById(R.id.layoutID);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
if(!items.contains(Position.getText())
{
items.add(Position.getText());
layout.setBackgroundColor(Color.parseColor("")); //input RGB value of selected item
}
else()
{
items.remove(Position.getText());
layout.setBackgroundColor(Color.parseColor("")); //Input RGB value of unselected colour
}
}
});
return itemView;
}
}
This will change the layout colour of the items you have clicked and add them to a list for when you would like to use them. It also changes the colour back after selection and removes the item from the list.
The ListAdapter class is as follows:
public class ListAdapter{
String text;
public ListAdapter(String text)
{
super();
this.text= text;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text= text;
}
}
I hope this helps. PS. listadapter.xml only holds a textview in a RelativeLayout.