Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On long click delete item

Tags:

android

I have ListView which is saving all data to database. For adding i have simple button and textBox which adds to database, and show to listView. Now i want thath on long item click (hold on item) will delete the selected item from list. How is possible to do thath (actualy what method to call for long click).

Here is current code:

import java.util.List;
import java.util.Random;

import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class Announce extends ListActivity{
    private CommentsDataSource datasource;
    EditText edit;
    ListView list;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.announce);

        datasource = new CommentsDataSource(this);
        datasource.open();

        List<Comment> values = datasource.getAllComments();

        ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
                android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }


    public void onClick(View view) {
        @SuppressWarnings("unchecked")
        ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
        Comment comment = null;
        switch (view.getId()) {
        case R.id.add:
            edit = (EditText)findViewById(R.id.editTxt);
            Editable txt=(Editable)edit.getText();
            String input = txt.toString();          
            comment = datasource.createComment(input);
            adapter.add(comment);
            break;  
        }
        adapter.notifyDataSetChanged();
    }



    @Override
    protected void onResume() {
        datasource.open();
        super.onResume();
    }

    @Override
    protected void onPause() {
        datasource.close();
        super.onPause();
    }

}
like image 709
HyperX Avatar asked Apr 07 '12 20:04

HyperX


2 Answers

You want a context menu basically see here: http://developer.android.com/guide/topics/ui/menus.html#context-menu

like image 64
EdChum Avatar answered Oct 06 '22 12:10

EdChum


You can use this contruct :D

something.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) { ... } });
like image 38
Nguyễn Hoàng Gia Avatar answered Oct 06 '22 13:10

Nguyễn Hoàng Gia