简体   繁体   中英

Display text when clicked on the Button of AlertDialog in android

I'm working with android and I want to make an event on AlertDialog button. I want to change the text on the button dynamically, this is my code

AlertDialog.Builder alert = new AlertDialog.Builder(Soto_Betawi.this);
            alert.setTitle("Payment");
            alert.setMessage("Total Price : Rp. " + total);
            final EditText input = new EditText(Soto_Betawi.this);
            alert.setView(input);
            alert.setPositiveButton("Change Due", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int which)
                {
                    cash = Integer.parseInt(input.getText().toString());
                    change = cash - total;
                    //I want to set a text from the operation above in a text
                }
            });
            alert.setNegativeButton("Close", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int which)
                {

                }
            });
            alert.setCancelable(true);
            alert.create().show();

Instead of using AlertDialog, you can use Activity with Dialog theme and create your own layout. So that you can simply change the text with

myButton.setText("your text");

Another Solution for you:

(AlertDialog)dialog.getButton(AlertDialog.BUTTON_POSITIVE)

This Should give you positive button of the AlertDialog

So my assumption is

(AlertDialog)dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText("Your Text");

should be your answer.

Create and show alertdialog from method:

public void showAlert(String txtPositiveButton) {
    AlertDialog.Builder alert = new AlertDialog.Builder(Soto_Betawi.this);
    alert.setTitle("Payment");
    alert.setMessage("Total Price : Rp. " + total);
    final EditText input = new EditText(Soto_Betawi.this);
    alert.setView(input);
    alert.setPositiveButton(txtPositiveButton, new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
            cash = Integer.parseInt(input.getText().toString());
            change = cash - total;
            //I want to set a text from the operation above in a text
        }
    });
    alert.setNegativeButton("Close", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
        }
    });
    alert.setCancelable(true);
    alert.create().show();
}

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