简体   繁体   中英

How to remove a item in listview?

I am creating a playlist with 2 lines of name and genre, how to I can delete it.

This is MainActivity :

String[] gene, sl;
...
adp = new Adapter(MainActivity.this, gene, sl);       
     lv.setAdapter(adp);   

This is Adapter

public class Adapter extends ArrayAdapter<String> {

   private final Activity context;
   private final String[] gene;
   private final String[] sl;

   SharedPreferences preferences;
   public Adapter(Activity context, String[] gene ,String[] sl) {     
   super(context, R.layout.activity_m , gene);

       this.context = context;
       this.gene = gene;
       this.sl = sl;
       }

private class ViewHolder{
  TextView txtgene, txtsl;
}
       @Override 
     public View getView(final int position, View view, ViewGroup parent) {       
       ViewHolder holder;       
       if (view == null) {       
        LayoutInflater inflater = context.getLayoutInflater();
        view = inflater.inflate(R.layout.activity_m, null, true);
     holder = new ViewHolder();        
     holder.txtgene = (TextView) view.findViewById(R.id.txtgene); 
     holder.txtsl = (TextView) view.findViewById(R.id.txtsl);

    view.setTag(holder);
      }else{
      holder = (ViewHolder) view.getTag();
      }
      if (gene[position] != null) {
    holder.txtgene.setText(gene[position]); 
    }
      holder.txtsl.setText(sl[position]);
       return view;
        }
    }

How to remove an item when you know its exact position ?

Thank !

You are using the ArrayAdapter constructor that takes an array. This in turn will create an immutable List internal to the ArrayAdapter. So, you will not be able to modify your adapter going this route.

Instead, make a new ArrayList from your array and call the ArrayAdapter constructor that takes a List.

So, change the super call in your Adapter constructor to this:

super(context, R.layout.activity_m, new ArrayList<>(Arrays.asList(gene)));

And then, when you want to remove an item given it's position, do this:

adp.remove(getItem(position));

PS: You should consider refactoring your gene and sl arrays into a class and then use it as the type of your List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM