Refresh or change the AlertDialog Message

会有一股神秘感。 提交于 2020-07-03 05:50:29

问题


I create an AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(this);
...
AlertDialog alert = builder.create();
alert.show();

After a moment I want to change the AlertDialog message without closing it.

Is it possible?


回答1:


Yes ,you can.

For example, if you create your own dialog, with your own layout, you can set an id for each of the views, and then access each of them (for example the textView) and set its new text whenever you wish to.




回答2:


Agreed with android developer. You can also use

TextView messageView = (TextView) alert.findViewById(android.R.id.message);

To get the control over the messageTextView of AlertDialog. Then you can set the new text there.




回答3:


Use alert.setMessage() instead of builder.setMessage(). Call alert.setMessage() and set message of your dialog anytime you want.

Example:

     AlertDialog.Builder dialogBuilder;
     AlertDialog alertDialog;

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       dialogBuilder = new AlertDialog.Builder(MainActivity.this);
       alertDialog = dialogBuilder.create();
     }


     public void showAlert(int caller) {
       if(alertDialog != null && !alertDialog.isShowing()) {
        switch (caller){
            case 1:
                alertDialog.setMessage("First method call");
                break;
            case 2:
                alertDialog.setMessage("Second method call");
                break;
            case 3:
                alertDialog.setMessage("Third method call");
                break;
            }
            alertDialog.show();
         }
      }



回答4:


Set OnClickListener out of main setter like this:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity())
                        .setTitle(getResources().getString(R.string.dialog_title))
                        .setMessage("Waiting ...")
                        .setNeutralButton(R.string.check, null);

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Button b_neutral = alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
b_neutral.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TextView tv_message = (TextView) alertDialog.findViewById(android.R.id.message);
                        tv_message.setText("Works ...");
    }
});


来源:https://stackoverflow.com/questions/16105920/refresh-or-change-the-alertdialog-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!