How to access message of AlertDialog built by Aler

2019-08-02 11:26发布

问题:

I have this AlertDialog and AlertDialog.Builder:

    String message = "A message";
    AlertDialog.Builder dBuilder = new AlertDialog.Builder(this);
    dBuilder.setMessage(message);
    ....
    AlertDialog myDialog = dBuilder.create();

Now I am writing a unit test and need to test the message of the dialog. How can I access that message?

回答1:

Give this a shot. Instead of initializing myDialog with dBuilder.create(), use the construction of the builder:

String message = "A message";
AlertDialog.Builder dBuilder = new AlertDialog.Builder(this);
AlertDialog myDialog = dBuilder
              .setMessage(message)
              .show();
TextView messageTextView = (TextView)myDialog.findViewById(android.R.id.message);
String dialogMessage = messageTextView.getText();


回答2:

Use a view to define a TextView and add the view inside the AlertDialog.Builder.

So now when you want to test the String inside the AlertDialog, just access it

view.textView.getText().toString();



回答3:

Try this

TextView textView = (TextView)myDialog.findViewById(android.R.id.message);
Log.e("TEST", ""+textView.getText());