长按从android listview中删除项目

时间:2018-02-25 01:10:19

标签: java android

我应该在onItemLongClick函数中写一下,以便在长按一下从列表视图中删除一个项目。以下是代码:

public class Favorites extends AppCompatActivity {

DBConnection db = new DBConnection(this);

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

     ListView listView = (ListView) findViewById(R.id.empList);
     ArrayList<String> arrayList = db.getAllRecords();
     listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,arrayList));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                        int position, long id) {



            return false;
        }

3 个答案:

答案 0 :(得分:2)

对于listView,你应该 setOnItemLongClickListener ,并在删除项目时定义适配器来更新数据

ListView listView = (ListView) findViewById(R.id.empList);
    final ArrayList<String> arrayList = db.getAllRecords();
    final ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,arrayList);
    listView.setAdapter(adapter);

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            arrayList.remove(i);
            adapter.notifyDataSetChanged();
            return true;
        }
    });

答案 1 :(得分:0)

在我的例子中,我使用自定义Adapter类作为将数据连接到ListView之间的过程。在这种情况下,它将类似于以下内容:

Adapter adapter = new Adapter(this, arrayList);
String s = (String) arrayList.get(position);
arrayList.remove(s);
adapter.notifyDataSetChanged();

再看看这个回购:

https://github.com/CarmenDelessio/Hour8Application/tree/master/app/src/main/java/com/bffmedia/hour8application

特别是,BaseAdapterActivity.java值得用作​​模型。

答案 2 :(得分:0)

您可以尝试从阵列列表中删除元素

arrayList.remove(position);