Center message in android dialog box

前端 未结 8 608
野趣味
野趣味 2020-11-29 01:53

I want the message text within my dialog box to be center aligned.

相关标签:
8条回答
  • 2020-11-29 02:20

    Of course, you can always set the gravity of the original text view. This allows you to not have to worry about formatting and padding.

    For example

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Title");
    builder.setMessage("Message");
    builder.setPositiveButton("OK", null);
    AlertDialog dialog = builder.show();
    
    // Must call show() prior to fetching text view
    TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
    messageView.setGravity(Gravity.CENTER);
    
    0 讨论(0)
  • 2020-11-29 02:34

    Building off of Chase's answer, here's how to also center the title. I think this is the easiest way. Why android doesn't center by default or make it a simple constructor param is beyond me.

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("My Title");
    builder.setMessage("My message");
    builder.setPositiveButton("OK", listener);
    AlertDialog dialog = builder.show();
    
    // Must call show() prior to fetching views
    TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
    messageView.setGravity(Gravity.CENTER);
    
    TextView titleView = (TextView)dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
    if (titleView != null) {
        titleView.setGravity(Gravity.CENTER);
    }
    
    0 讨论(0)
提交回复
热议问题