Search code examples
androidandroid-arrayadapterandroid-adapterbaseadapterlistadapter

Remove a list-item on click inside a custom adapter


I have a custom ArrayAdapter in which i am using two different Layout.

List item 1 have a different layout and other list item have same layout.

List item one have a layout which include button and textview. I want List item one to be removed when someone clicked the button inside it.

class MyAdapter extends ArrayAdapter<Product> {

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

@Override
public int getItemViewType(int position) {
    if (position == 0) {
        return VIEW_TYPE0;
    }
    return VIEW_TYPE1;
}

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

    final Product product = getItem(position);

    if (convertView == null) {
        if (getItemViewType(position) == VIEW_TYPE0) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.layout1, parent, false);
        } else {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.layout2, parent, false);
        }
    }

    TextView textview1;
    TextView textview2;
    Button button1;

    if (position == 0) {
        button1 = (Button) convertView.findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              // delete this first list item here
            }
        });
    } else {
        textview = (TextView) convertView.findViewById(R.id.textview1);
        textview.setText(product.product_name);
    }
    return convertView;
}

Solution

  • Try it as using remove method of List and call notifyDataSetChanged :

        public void onClick(View v) {
          // delete this first list item here
           products.remove(0);
           notifyDataSetChanged();
        }