簡體   English   中英

無法使用Android中的上下文菜單從列表視圖中刪除項目

[英]Unable to delete item from List View using context menu in Android

我有自定義列表視圖,其中包含員工的姓名和用戶名。 我正在嘗試刪除任何員工。 我已使用上下文菜單刪除員工。 但是我沒有在列表視圖中獲得所選項目的ID。 這是我的EmployeeDatabaseHelper類,其中包含deleteEmployee方法

EmployeeDatabaseHelper .java

public void deleteEmployee(String id){

    SQLiteDatabase db = dbhelper.getReadableDatabase();
    int delId = db.delete(TABLE_NAME_EMPLOYEE, id+" =? ", 
            new String[] {String.valueOf(id)});
    db.close();
}

我在這里使用上下文菜單刪除員工

EmployeeFragment.java

public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {

    menu.setHeaderTitle("Select Action");
    menu.add(0,v.getId(),0,"Edit");
    menu.add(0,v.getId(),0,"Delete");
}

public boolean onContextItemSelected(MenuItem item) {

    if (item.getTitle() == "Edit"){
        //ToDo edit employee Code
    } else if (item.getTitle() == "Delete") {

        new AlertDialog.Builder(getActivity())
        .setTitle("Delete")
        .setMessage("Are you sure you want to delete this Employee ?")
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dbHelper.deleteEmployee(id);
                //id is not getting here. (My issue)
            }
        })
        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();

    } else {
        return false;
    }
    return true;
}

這是我的模特班雇員

Employee.java

public class Employee {
    public String username;
    public String name;
    public String password;     
}

如果要刪除ListView Item,則應從適配器中刪除該ListView所使用的Item。

看看是否要使用onCreateContextMenuListView刪除項目,您可以這樣做:

int currentposition;

listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        currentposition = info.position;
        menu.setHeaderTitle("Choose");
        menu.add(0, v.getId(), 0, "Delete ");

    }

});

現在使用這個:

public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
            .getMenuInfo();
    if (item.getTitle() == "Delete ") {
        mArray.remove(currentposition);
        ca.notifyDataSetChanged();
        Toast.makeText(this, "Deleted ", Toast.LENGTH_SHORT)
                .show();
    } 
    return true;
}

暫無
暫無

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

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