theblitz theblitz - 1 month ago 12x
Android Question

Right justify text in AlertDialog

Is it possible to right-justify the text in an AlertDialog's title and message?

I am showing Hebrew messages but they are showing up left justified.


As far as I can see from the code of AlertDialog and AlertController you can't access the TextViews responsible for message and title.

You can use reflection to reach mAlert field in AlertDialog instance, and then again use reflection to access mMessage and mTitle fields of mAlert. Though I wouldn't recommend this approach as it relies on internals (which might change in future).

As another (and probably much better) solution, you can apply custom theme via AlertDialog constructor. This would allow you to right-justify all TextViews in that dialog.

     protected AlertDialog (Context context, int theme)

This should be easier and more robust approach.

Here is step by step instructions:

Step 1. Create res/values/styles.xml file. Here its content:

<?xml version="1.0" encoding="utf-8"?>

    <style name="RightJustifyTextView" parent="@android:style/Widget.TextView">
        <item name="android:gravity">right|center_vertical</item>

    <style name="RightJustifyDialogWindowTitle" parent="@android:style/DialogWindowTitle" >
         <item name="android:gravity">right|center_vertical</item>

    <style name="RightJustifyTheme" parent="@android:style/Theme.Dialog.Alert">
        <item name="android:textViewStyle">@style/RightJustifyTextView</item>       
        <item name="android:windowTitleStyle">@style/RightJustifyDialogWindowTitle</item>       


Step 2. Create file. Here its content:

public class RightJustifyAlertDialog extends AlertDialog
    public RightJustifyAlertDialog(Context ctx)

Step 3. Use RightJustifyAlertDialog dialog:

AlertDialog dialog = new RightJustifyAlertDialog(this);
dialog.setButton("button", new OnClickListener()
    public void onClick(DialogInterface arg0, int arg1)

dialog.setTitle("Some Title");
dialog.setMessage("Some message");;

Step 4. Check the results:

enter image description here