简体   繁体   English

如何在 ListView 中长时间选择项目以删除它们?

[英]How can I long select items in ListView to delete them?

Just trying to create a simple app that would allow users to input notes and save them into the List view.只是试图创建一个简单的应用程序,允许用户输入笔记并将它们保存到列表视图中。 What code would I need to implement to allow the user to longClick something in the list to delete it.我需要实现什么代码才能允许用户长按列表中的某些内容来删除它。

public class Notes extends AppCompatActivity {

Button save;
ArrayList<String> addArray = new ArrayList<String>();
EditText txt;
ListView show;


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

    txt = (EditText) findViewById(R.id.textInput);
    show = (ListView) findViewById(R.id.listView);
    save = (Button) findViewById(R.id.saveButton);

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(Notes.this, android.R.layout.simple_list_item_1, addArray);

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String getInput = txt.getText().toString();

            if (addArray.contains(getInput)) {
                Toast.makeText(getBaseContext(), "Note already added!", Toast.LENGTH_LONG).show();
            } else if (getInput == null || getInput.trim().equals("")) {
                Toast.makeText(getBaseContext(), "Input required!", Toast.LENGTH_LONG).show();
            } else {
                addArray.add(getInput);

                show.setAdapter(adapter);
                ((EditText) findViewById(R.id.textInput)).setText(" ");
            }
        }
    });


    show.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {

            return true;
        }
    });
}

} }

That might solve your problem:这可能会解决您的问题:

addArray.remove(pos);
adapter.notifyOnDataSetChanged();

You could make use of Contextual Menus or Contextual Action Mode.您可以使用上下文菜单或上下文操作模式。

Go through this tutorial : http://developer.android.com/guide/topics/ui/menus.html#context-menu通过本教程: http : //developer.android.com/guide/topics/ui/menus.html#context-menu

Then you could delete the item from adapter and notify lostview using adapters Notifydatasetchanged method.然后您可以从适配器中删除该项目并使用适配器 Notifydatasetchanged 方法通知 lostview。

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

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