Darsen Lu Darsen Lu - 1 month ago 24
Android Question

Setting message text appearance in Alert Dialog using XML (Android API Level 23)

I was trying to set the text size of message in an alert dialog, but was unable to after many attempts. On the other hand, the title and button text sizes can be controlled by the theme's font size simultaneously (set to 14sp in the example below).

The alert dialog was created using the following XML style description, following the approach described in this blog:

<style name="MyAlertDialogTheme" parent="@android:style/Theme.Holo.Dialog.NoActionBar">
<item name="colorAccent">#ffffff</item>

<!--This controls size of button & title text-->
<item name="android:textSize">14sp</item>

<item name="android:textAppearanceMedium">@style/MyMsgTextAppearance</item>
</style>
<style name="MyMsgTextAppearance" parent="@android:style/TextAppearance.Holo.Medium">
<item name="android:textSize">22sp</item>
<item name="android:textStyle">italic</item>
</style>


The theme was invoked at runtime using this code:

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogTheme);
builder.setCancelable(false);
builder.setTitle("Remove contact");
builder.setMessage("Are you sure you want to delete this contact ?");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);

AlertDialog dialog = builder.create();
dialog.show();


Here is what I got:
Alert dialog screenshot

Apparently, the message text size is much smaller than 22sp. I could, however, adjust the font size during runtime:

dialog.show();

TextView tv = (TextView) dialog.findViewById(android.R.id.message);
if(tv != null)
tv.setTextSize(22.0f);


Update
It turns out that if I import android.app.AlertDialog, the message size can be adjusted using this method. However, if I import android.support.v7.app.AlertDialog, it can't be adjusted using this method.

Answer

appcompat-v7 AlertDialog message TextView has hardcoded style @style/TextAppearance.AppCompat.Subhead instead of ?android:textAppearanceMedium. You cannot change its text appearance by overriding the theme attribute.

However you can customize the layout used by appcompat-v7 AlertDialog.

res/values/styles.xml

<style name="AppTheme" parent="Theme.AppCompat">
    <item name="alertDialogStyle">@style/AlertDialog.Custom</item>
    <item name="alertDialogTheme">@style/AlertDialogTheme</item>
</style>

<style name="AlertDialog.Custom" parent="AlertDialog.AppCompat">
    <item name="android:layout">@layout/alert_dialog_custom</item>
</style>

<style name="AlertDialogTheme" parent="Theme.AppCompat.Dialog.Alert">
    ...
</style>

res/layout/alert_dialog_custom.xml

Make a copy of abc_alert_dialog_material.xml (find via double-shift in Android Studio), find a TextView with @android:id/message and alter it as you please.