簡體   English   中英

如何使用按鈕從列表視圖中刪除項目?

[英]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;
        }

    }

}

如何從自定義列表視圖中刪除特定項目。 我在自定義列表視圖中添加了按鈕。 我想使用該位置上的特定按鈕刪除項目。

至於刪除東西,你需要從ADAPTER刪除而不是列表。 您不需要保留自己的項目副本(除非您將其用於其他項目),因為數組中有一個項目列表。 你需要調用adapter.remove(item)而不是list.remove(item)

那你只需使用ArrayAdapter的remove()方法從列表中刪除所需的項目。

可能的方法是:

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

另一種方法是修改ArrayList並在ArrayAdapter上調用notifyDataSetChanged()。

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

您好,請嘗試以下代碼從Listview中刪除項目

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM