【问题标题】:How do I remove an item from a listview using the button inside?如何使用里面的按钮从列表视图中删除一个项目?
【发布时间】:2015-02-17 00:30:35
【问题描述】:

我查看了很多示例并设法做到了这一点,但我仍然无法获得从数组中删除项目的按钮。如何正确使用 remove(position)?

公共类适配器扩展 ArrayAdapter {

public adapter(Context context, ArrayList<User> users) {

    super(context, 0, users);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {


    User user = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
    }

    TextView question = (TextView) convertView.findViewById(R.id.question);
    TextView answer = (TextView) convertView.findViewById(R.id.answer);

    question.setText(user.name);
    answer.setText(user.hometown);

    ImageButton remove = (ImageButton) convertView.findViewById(R.id.removeButton);

    remove.setTag(position);

    remove.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {


            notifyDataSetChanged();}
        });

    return convertView;


    }
}

用户列表

public class User {
public String name;
public String hometown;

public User(String name, String hometown) {
    this.name = name;
    this.hometown = hometown;
}

public static ArrayList<User> getUsers() {
    ArrayList<User> users = new ArrayList<>();
    users.add(new User("Hi", "hi"));
    users.add(new User("Marla", "San Francisco"));
    users.add(new User("Sarah", "San Marco"));
    return users;
}

}

【问题讨论】:

  • 你的日志猫在哪里???
  • 我没有保留日志,但是在更改了一些内容之后,我认为这是由于错误地使用了 remove(position)。我如何正确实现这一点?

标签: android android-listview android-arrayadapter


【解决方案1】:
  1. 将位置作为 TAG 分配给 GetView 中的按钮
  2. 按钮的 OnClick,从 ArrayList 中删除该位置项
  3. 要刷新ListView UI,调用adapter.notifyDataSetChanged()方法

这对你有帮助, Delete a ListItem by clicking the ImageView within the ListItem

【讨论】:

    【解决方案2】:

    你有 ArrayList 用户

    在特定事件上删除用户arrayList的对象,然后简单地调用dapter.notifyDataSetChanged()方法。

    【讨论】:

    • 我之前试过 users.remove(position) 但没用
    【解决方案3】:
    1. 在您的适配器类中添加此方法。
      public void removeItem(int position){
      arrayList.remove(位置);
      notifyDataSetChanged();
      }
    2. 从类似按钮的 onClick 调用上述方法。
      remove.setOnClickListener(new
      View.OnClickListener(){
      @Override
      public void onClick(查看视图) { 删除项目(位置);}
      });
    3. 参考链接:Listview delete item and Refresh - android

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多