Search code examples
androidbuttonandroid-edittextonlongclicklistener

Allow User to edit button text on long click in Android


I want to allow the App users to change the Button text in Android. When User clicks Button, it should do something but when he/she LongClicks the button, an edittext should pop-up & whatever user types into it should get saved as Button Text. So far I have completed following thing.

btn1 = (Button) findViewById(R.id.button1);
etLabel = (EditText) findViewById(R.id.etName);

btn1.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // How to pop-up edittext from here 
                // to allow user change Button name
                btn1.setText(name);
                return true;
            }
        });
    }

    public void onButtonClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                // do something else here
                break;
    }
 }

Solution

  • try like this:

    public class SOdemoAcitvity extends AppCompatActivity {
    
    private Button btn;
    private EditText edit;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.so_demo);
        btn = (Button) findViewById(R.id.btn_demo);
        edit = (EditText) findViewById(R.id.edit_text);
    
        btn.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showDialog(edit.getText().toString());
    
                return true;
            }
    
    
        });
    }
    
    private void showDialog(String str) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("input text");
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_view, null);
        final EditText edit_dialog = (EditText) view.findViewById(R.id.edit_dialog);
        edit_dialog.setText(str);
        builder.setView(view);
        builder.setNegativeButton("cancel",null);
        builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                        btn.setText(edit_dialog.getText().toString());
            }
        });
        builder.show();
    }
    }
    

    dialog_view xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">
    
    <EditText
    android:id="@+id/edit_dialog"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    </LinearLayout>
    

    enter image description here

    and then

    enter image description here