简体   繁体   中英

How to delete item from listview using button?

List_Remind.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <TextView
        android:id="@+id/label"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:layout_weight="1"
        android:textSize="30px" >
    </TextView>

    <ImageButton
        android:background="@null"
        android:id="@+id/imageButton1"
        android:layout_width="50px"
        android:layout_height="50px"
        android:layout_marginRight="10dp"
        android:src="@drawable/delete_task" />

</LinearLayout>

ReminderListActivity.java

package com.dummies.android.taskreminder;

import com.dummies.android.taskreminder.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class ReminderListActivity extends Activity implements OnClickListener{
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private RemindersDbAdapter mDbHelper;
    ListView lvRemind;
    ImageButton btnAdd,btnBack,btnSettings;
    TextView text;
    LinearLayout layout;
    ArrayAdapterExample aAdapter;
    int pos;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);
      //  setContentView(R.layout.reminder_list);
        LayoutInflater inflate = LayoutInflater.from(this);
        layout = (LinearLayout)inflate.inflate(R.layout.main, null);
        this.setContentView(layout); 
        btnAdd = (ImageButton) findViewById(R.id.btnAdd);
        btnBack = (ImageButton) findViewById(R.id.btnBackMain);
        btnSettings = (ImageButton) findViewById(R.id.btnSettings);

        btnAdd.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        btnSettings.setOnClickListener(this);
        mDbHelper = new RemindersDbAdapter(this);
        mDbHelper.open();
        fillData();

        lvRemind.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
//                Intent i = new Intent(ReminderListActivity.this, ReminderEditActivity.class);
//              i.putExtra(RemindersDbAdapter.KEY_ROWID, arg2);
//          startActivityForResult(i, ACTIVITY_EDIT); 
            //  Toast.makeText(ReminderListActivity.this, "Hello", Toast.LENGTH_LONG).show();
            }
        });


    }


    private void fillData() {
        Cursor remindersCursor = mDbHelper.fetchAllReminders();
        startManagingCursor(remindersCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text1};

        // Now create a simple cursor adapter and set it to display
//        SimpleCursorAdapter reminders = 
//              new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
//        setListAdapter(reminders);

        text = (TextView)findViewById(R.id.TextView02); 


        lvRemind = (ListView)findViewById(R.id.alist);

        aAdapter = new ArrayAdapterExample(ReminderListActivity.this, mDbHelper.fetchAllReminders());

        lvRemind.setAdapter(aAdapter);


    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater mi = getMenuInflater(); 
        mi.inflate(R.menu.list_menu_item_longpress, menu); 
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
        case R.id.menu_delete:
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
            mDbHelper.deleteReminder(info.id);
            fillData();
            return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createReminder() {
        Intent i = new Intent(this, ReminderEditActivity.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

//    @Override
//    protected void onListItemClick(ListView l, View v, int position, long id) {
//        super.onListItemClick(l, v, position, id);
//        Intent i = new Intent(this, ReminderEditActivity.class);
//        i.putExtra(RemindersDbAdapter.KEY_ROWID, id);
//        startActivityForResult(i, ACTIVITY_EDIT); 
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnAdd:
            createReminder();
            break;
        case R.id.btnSettings:
            Intent i = new Intent(this, TaskPreferences.class); 
            startActivity(i);
            break;
        case R.id.btnBackMain:
            onBackPressed();
            break;
        default:
            break;
        }

    }

    @SuppressLint("NewApi")
    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

     class ArrayAdapterExample extends CursorAdapter {

        public ArrayAdapterExample(Context context, Cursor c) {

            super(context, c);

        }


        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // TODO Auto-generated method stub
             TextView textViewPersonName = (TextView) view.findViewById(R.id.label);

                textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));

                Log.d("Index: ", ""+cursor.getPosition());
                pos = cursor.getPosition();
             ImageButton ibDel =(ImageButton)view.findViewById(R.id.imageButton1);
             ibDel.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
            //      Toast.makeText(ReminderListActivity.this, "Hello", Toast.LENGTH_SHORT).show();

                    lvRemind.setOnItemClickListener(new OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1,
                                int arg2, long arg3) {
                            // TODO Auto-generated method stub
                            Toast.makeText(ReminderListActivity.this, ""+lvRemind.getItemAtPosition(arg2), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // TODO Auto-generated method stub
             LayoutInflater inflater = LayoutInflater.from(parent.getContext());

                View retView = inflater.inflate(R.layout.list_remind, parent, false);

                return retView;
        }

    }

}

How can I delete particular item from custom listview. I have added button in custom listview. I want to delete item using particular button on that position.

As for deleting stuff, you need to delete from the ADAPTER not a list. You don't need to keep your own copy of the items (unless you are using them for something else) because there is a list of item inside the array. you need to call adapter.remove(item) instead of list.remove(item)

Well you just remove the desired item from the list using the remove() method of your ArrayAdapter .

A possible way to do that would be:

Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);

Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.

arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();

Hi try the following code to delete the Item from Listview

Button button1 = (Button) findViewById(R.id.create_message);
button1.setOnClickListener(new OnClickListener()
 public void onClick(View v)
   {
     MyDataObject.remove(positionToRemove);
     adapter.notifyDataSetChanged();
   }       
 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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