简体   繁体   English

如何在列表视图中删除项目?

[英]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 : 这是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. 您正在使用采用数组的ArrayAdapter构造函数。 This in turn will create an immutable List internal to the ArrayAdapter. 反过来,这将在ArrayAdapter内部创建一个不可变的List。 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. 而是从您的数组中创建一个新的ArrayList,然后调用采用List的ArrayAdapter构造函数。

So, change the super call in your Adapter constructor to this: 因此,将您的Adapter构造函数中的超级调用更改为:

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. PS:您应该考虑将基因和sl阵列重构为一个类,然后将其用作列表的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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