ListView Multiselection

社会主义新天地 提交于 2019-11-29 07:57:07

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<ListAdapter> CustomAdapterList = new ArrayList<CustomAdapterList>();//List  with items to send to the custom adapter

List<String> items = new ArrayList<String>();
private void populateCustomList()
{
    ArrayAdapter<ListAdapter> Population= new CustomAdapter();
    ListView list= (ListView)findViewById(R.id.listView);
    list.setAdapter(Population);
}

private class CustomAdapter extends ArrayAdapter<ListAdapter>
{
    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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!