如何在单击按钮时从ArrayList和ArrayAdapter中删除所选项目?

时间:2019-06-21 14:48:02

标签: java android android-listview android-listadapter

我有一个带有自定义列表布局的ListView。我为此使用ArrayList和ArrayAdapter。我很难从arraylist中删除选定的项目。我不确定要我做错了。这是我拥有的一个数组列表的示例:

项目A

项目B

项目C

项目D

让我们说我选择了按钮C,然后单击标签为“删除”的项目C,然后将项目C从列表中删除。我该如何完成?目前,我的代码仅删除索引0上的项目。我希望删除选定的项目索引。

这是我的密码...

Java类:

public class MainActivity extends AppCompatActivity {

ListView lstVw;
Button addBtn, removeBtn, clearListBtn;

ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
int getPosition = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lstVw = findViewById(R.id.lstView);
    addBtn = findViewById(R.id.add_item_btn);
    removeBtn = findViewById(R.id.remove_item_btn);
    clearListBtn = findViewById(R.id.clear_list_btn);

    arrayList = new ArrayList<>();
    adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, R.id.item_tv, arrayList);
    lstVw.setAdapter(adapter);



    lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String getItem = adapter.getItem(position);
            getPosition = Integer.parseInt(getItem);
        }
    });

    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
            adb.setTitle("Enter Item Name");
            final EditText itemTxt = new EditText(MainActivity.this);
            itemTxt.setText(getString(R.string.default_item_name_value));
            itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
            adb.setView(itemTxt);

            adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String getItem = itemTxt.getText().toString();

                    Set<String> s = new LinkedHashSet<>(arrayList);
                    if (s.contains(getItem)) {
                        arrayList.clear();
                        arrayList.addAll(s);
                        Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
                    } else {
                        arrayList.add(getItem);
                        adapter.notifyDataSetChanged();
                    }
                }
            });

            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            adb.create();
            adb.show();
        }
    });

    clearListBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!arrayList.isEmpty()) {
                arrayList.clear();
                adapter.notifyDataSetChanged();
            }
        }
    });


    removeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String getItem = arrayList.get(getPosition);
            arrayList.remove(getItem);
            adapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
        }
    });

}

}

主要XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="650dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="650dp">

        <ListView
            android:id="@+id/lstView"
            android:layout_width="match_parent"
            android:layout_height="650dp"
            tools:ignore="NestedScrolling" />

    </RelativeLayout>
</ScrollView>

<include layout="@layout/action_buttons"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"/>

操作按钮XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center|top">

<Button
    android:id="@+id/add_item_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:textAllCaps="false"
    android:text="@string/add_item_text"
    android:textSize="14sp"
    android:textStyle="bold"
    android:textColor="@android:color/black"/>

<Button
    android:id="@+id/remove_item_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toEndOf="@id/add_item_btn"
    android:textAllCaps="false"
    android:text="Remove Item"
    android:textColor="@android:color/black"
    android:textSize="14sp"
    android:textStyle="bold"/>

<Button
    android:id="@+id/clear_list_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toEndOf="@id/remove_item_btn"
    android:textAllCaps="false"
    android:text="@string/clear_list_text"
    android:textSize="14sp"
    android:textStyle="bold"
    android:textColor="@android:color/black"/>

我的自定义列表布局XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


<TextView
    android:id="@+id/item_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:textSize="20sp"
    android:textColor="@android:color/black"/>

</ScrollView>

感谢您的帮助!谢谢!

2 个答案:

答案 0 :(得分:0)

在我看来,您的int getPosition = 0;变量没有更新为您的新职位。在您的点击监听器上,您正在尝试将所选项目的值解析为Integer,也许您可​​以尝试仅使用当前位置进行更新?

lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        getPosition = position;
    }
});

编辑:

您可以使用类似这样的内容:

创建一个接口,您的活动将实现该接口,适配器将使用该接口来通知职位变更:

public interface PositionChangeListener {
    void onPositionChanged(int newPosition);
}

创建自定义适配器:

public class CustomAdapterView extends BaseAdapter {

private Context context;
private PositionChangeListener listener;
private ArrayList<String> items;

public CustomAdapterView(Context context, ArrayList<String> items, PositionChangeListener listener) {
    this.context = context;
    this.items = items;
    this.listener = listener;
}

@Override
public int getCount() {
    return items.size();
}

@Override
public Object getItem(int position) {
    return items.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;

    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate( R.layout.item_list, null);
        viewHolder = new ViewHolder();
        viewHolder.txt = convertView.findViewById(R.id.item_tv);
        viewHolder.txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onPositionChanged(position);
            }
        });
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.txt.setText(items.get(position));
    return convertView;
}

private class ViewHolder {
    TextView txt;
}

}

现在在您的活动中:

public class MainActivity extends AppCompatActivity implements PositionChangeListener{

ListView lstVw;
Button addBtn, removeBtn, clearListBtn;

ArrayList<String> arrayList;
BaseAdapter adapter;
int getPosition = 0;

@Override
public void onPositionChanged(int newPosition) {
    getPosition = newPosition;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lstVw = findViewById(R.id.lstView);
    addBtn = findViewById(R.id.add_item_btn);
    removeBtn = findViewById(R.id.remove_item_btn);
    clearListBtn = findViewById(R.id.clear_list_btn);

    arrayList = new ArrayList<>();
    adapter = new CustomAdapterView(this, arrayList, this);
    lstVw.setAdapter(adapter);

    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
            adb.setTitle("Enter Item Name");
            final EditText itemTxt = new EditText(MainActivity.this);
            itemTxt.setText("default item name");
            itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
            adb.setView(itemTxt);

            adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String getItem = itemTxt.getText().toString();

                    Set<String> s = new LinkedHashSet<>(arrayList);
                    if (s.contains(getItem)) {
                        arrayList.clear();
                        arrayList.addAll(s);
                        Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
                    } else {
                        arrayList.add(getItem);
                        adapter.notifyDataSetChanged();
                    }
                }
            });

            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            adb.create();
            adb.show();
        }
    });

    clearListBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!arrayList.isEmpty()) {
                arrayList.clear();
                adapter.notifyDataSetChanged();
            }
        }
    });


    removeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String getItem = arrayList.get(getPosition);
            arrayList.remove(getItem);
            adapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
        }
    });

}

}

答案 1 :(得分:0)

removeBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String getItem = arrayList.get(getPosition);
        arrayList.remove(getItem);
        adapter.notifyDataSetChanged();
        Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
    }
});

您从哪里获得此getPosition?