Remove item from custom listview on button click

后端 未结 4 722
我在风中等你
我在风中等你 2021-01-02 23:34

I have a custom listview, that has 2 textviews and 2 buttons (play and delete button) I want when I click the delete button to delete the current line.

My adapter cl

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 00:08

    This code worked absolutely fine for me.

    public class CustomAdapter extends ArrayAdapter
    {
    Context c1;
    String s1[];
    int s2[];
    CustomAdapter(Context c,String s[],int s3[])
    {
        super(c,R.layout.tcustom,s);
        this.c1=c;
        this.s1=s;
        this.s2=s3;
    }
    
    public View getView(int position,View v,ViewGroup parent)
    {
        LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
        v=li.inflate(R.layout.tcustom,null);
        TextView tv=(TextView)v.findViewById(R.id.textView);
        ImageView im=(ImageView)v.findViewById(R.id.imageview);
        tv.setText(s1[position]);
        im.setImageResource(s2[position]);
    
        Button bt = (Button) v.findViewById(R.id.button);
        bt.setTag(position); //important so we know which item to delete on button click
    
        bt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v)
            {
                v.setVisibility(View.GONE);
                notifyDataSetChanged();
    
    
                int positionToRemove = (int)v.getTag(); //get the position of the view to delete stored in the tag
                removeItem(positionToRemove); //remove the item
            }
        });
    
        return v;
    }
    
    public void removeItem(int position){
        //convert array to ArrayList, delete item and convert back to array
        ArrayList a = new ArrayList<>(Arrays.asList(s1));
        a.remove(position);
        String[] s = new String[a.size()];
        s=a.toArray(s);
        s1 = s;
        notifyDataSetChanged(); //refresh your listview based on new data
    
    }
     public int getCount() {
      return s1.length;
     }
     public String getItem(int position) {
     return s1[position];
     }}
    

提交回复
热议问题