Search code examples
androidlistviewandroid-listviewonresume

Renaming an item in a listview


I have a ListView that contains the list of notes I have created.

I have overridden the method onItemLongClick(), which shows two options: Delete and Rename.

For the Rename option I want that a dialog be shown with a EditText and two buttons: Save or Cancel, so that user can change the name of any note he desires.

I know this can be done using dialogs but don't exactly know how to implement it.

Please explain how I can achieve this.


Solution

  • Show a dialog with two buttons and edit text.And you have to do something like this

    listView.setOnItemLongClickListener(new OnItemLongClickListener() {
    
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
    
                AlertDialog.Builder alert = new AlertDialog.Builder(
                        Activity.this);
                alert.setTitle("Rename");
    
                final EditText input = new EditText(Activity.this);
                alert.setView(input);
    
    
                alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String srt1 = input.getEditableText().toString();
                    //update your listview here 
    
                    }
                });
    
                alert.setNegativeButton("CANCEL",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alertDialog = alert.create();
                alertDialog.show();
                return false;
            }
        });
    
    }