22

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.

theblitz
  • 6,683
  • 16
  • 60
  • 114
  • I used this method: http://stackoverflow.com/questions/14439538/how-can-i-change-the-color-of-alertdialog-title-and-the-color-of-the-line-under/23278774#23278774 – mrd abd Apr 24 '14 at 20:10

7 Answers7

30

This is an old question, but there is a very simple solution. Assuming you are using MinSdk 17, you can add this to your styles.xml:

<style name="AlertDialogCustom" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="android:layoutDirection">rtl</item>
</style>

And in the AlertDialog.Builder you just need to specify this AlertDialogCustom in the constructor:

new AlertDialog.Builder(this, R.style.AlertDialogCustom)
                    .setTitle("Your title?")
                    .show();
MMG
  • 3,226
  • 5
  • 16
  • 43
yshahak
  • 4,996
  • 1
  • 31
  • 37
  • 1
    I pretty much like your solution and it changes everything including buttons, but title and message text are not showing, any tips? – mohas Jul 02 '19 at 19:35
  • 4
    use `parent="ThemeOverlay.AppCompat.Dialog.Alert"` for setting your theme in custom alert dialog. – Aref Jul 10 '19 at 13:05
18

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"?>
<resources>

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

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

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

</resources>

Step 2. Create RightJustifyAlertDialog.java file. Here its content:

public class RightJustifyAlertDialog extends AlertDialog
{
    public RightJustifyAlertDialog(Context ctx)
    {
        super(ctx,  R.style.RightJustifyTheme);
    }
}

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");

dialog.show();

Step 4. Check the results:

enter image description here

Gilbert
  • 868
  • 8
  • 14
inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • Do I have to define all the theme or is there a base line I can build on? I haven't used themes before. – theblitz May 25 '11 at 21:55
  • 1
    You can inherit the default theme and just add your changes. For example, in your `styles.xml` you could create a new theme called `CustomTheme` and start it like this:` – Femi May 25 '11 at 21:59
  • I tried doing mydialog = new AlertDialog.Builder(this,R.style.MyDialogTheme) but it claims that the constructor doesn't exists. – theblitz May 26 '11 at 00:37
  • No, unfortunatelly 'AlertDialog.Builder(Context, int theme)` was introduced only in API Level 11. You should use `AlertDialog(Context, int theme)` instead, and configure the dialog manually. – inazaruk May 26 '11 at 06:21
  • Is there any example out there of configuring manually? Also, what option should I be setting in the theme in order to make the fields right justified? Should I build my own XML file and use it as the layout? – theblitz May 26 '11 at 10:34
  • I am still seriously stuck here. Not sure how to get to the text and title fields (in order to right-justify them) even if I define a custom AlertDialog. – theblitz May 26 '11 at 18:36
  • I've added detailed step-by-step instructions to the question. Try it out. – inazaruk May 26 '11 at 19:21
  • Thx! You are awesome! Works wonderful. Just one small thing. It fills the whole screen instead of just being a pop-up in the middle. – theblitz May 26 '11 at 20:05
  • It shouldn't. At least in my project it was centered. Try doing all the steps above in new clean project. – inazaruk May 26 '11 at 20:10
  • Same happens in a clean project – theblitz May 26 '11 at 20:23
  • I cann't reproduce this in my environment. Could you maybe download you project somewhere and post link here? – inazaruk May 26 '11 at 20:33
  • Weird thing is that it works OK on Eclipse in the AVD emulator. However, as soon I as install it on my device (Xperia X10a) it goes weird. – theblitz May 26 '11 at 21:27
  • It might be because of different API Levels. What is your Xperia Android SDK version? – inazaruk May 26 '11 at 21:36
  • My phone says Firmware: 2.1-update1 which is what I am using in the emulator. Also, it is only this that has the problems. A "normal" AlterDialog" is ok. – theblitz May 26 '11 at 21:38
  • I'm really confused. The last thing you can try is changing your `default.properties` file: replace target value with `target=android-9`. – inazaruk May 26 '11 at 22:26
  • I am assuming u mean android-7 since that is equivalent to 2.1-update1 – theblitz May 26 '11 at 23:00
  • Yes, change it to android-9. See if it helps. I see different behaviors of dialog with different values. – inazaruk May 26 '11 at 23:04
  • Nope - no change. Super-weird. – theblitz May 26 '11 at 23:25
  • Still stuck here if anyone can help. – theblitz May 29 '11 at 12:22
  • I wasn't able to resolve the issue you had. Make screenshots with new theme applied and create new question with all the steps you did and other details you described here is comments. Maybe somebody else will be able to help you. – inazaruk May 29 '11 at 12:29
  • 1
    Ok - thanks. I'll also upload the mini-project I created and give a link to it. – theblitz May 29 '11 at 13:19
  • 1
    this is not working on the AppCompat them and dialog – Firas Al Mannaa Feb 21 '17 at 12:55
  • This no longer works, aapt gives an error: @android:style/DialogWindowTitle is private, and also resource android:style/Theme.Dialog.Alert is private. – Ali Nadalizadeh Oct 19 '18 at 15:06
17

If you want a quick and easy way to do this, I would just create and modify the default alert using AlertDialog.Builder. You can even create a convenience method and class like so:

/** Class to simplify display of alerts. */
public class MyAlert {

    public static void alert(Context context, String title, String message, OnClickListener listener)
    {
        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.RIGHT);

        TextView titleView = (TextView)dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
        if (titleView != null) {
            titleView.setGravity(Gravity.RIGHT);
       }
    }
}

Of course you could also change the gravity to CENTER for center alignment instead of right or the default left.

n8tr
  • 5,018
  • 2
  • 32
  • 33
  • Works great, but I got another problem. Title & text are aligned fine, but buttons aren't. How to get buttons by id? – Jjang Nov 09 '15 at 22:53
3

After struggling with this for an hour (the solutions above didn't work for me), I managed to align the AlertDialog's title and message to the right, without overriding any styles, simply changing the gravity and layout params.

In DialogFragment:

@Override
public void onStart() {
    super.onStart();

    // Set title and message
    try {
        alignDialogRTL(getDialog(), this);
    }
    catch (Exception exc) {
        // Do nothing
    }
}

The actual function:

public static void alignDialogRTL(Dialog dialog, Context context) {
    // Get message text view
    TextView message = (TextView)dialog.findViewById(android.R.id.message);

    // Defy gravity
    message.setGravity(Gravity.RIGHT);

    // Get title text view
    TextView title = (TextView)dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));

    // Defy gravity (again)
    title.setGravity(Gravity.RIGHT);

    // Get title's parent layout
    LinearLayout parent = ((LinearLayout)Title.getParent());

    // Get layout params
    LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams)parent.getLayoutParams();

    // Set width to WRAP_CONTENT
    originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;

    // Defy gravity (last time)
    originalParams.gravity = Gravity.RIGHT |  Gravity.CENTER_VERTICAL;

    // Set updated layout params
    parent.setLayoutParams(originalParams);
}
Elad Nava
  • 7,746
  • 2
  • 41
  • 61
1

The kotlinish way :

val alertDialog = alertDialogBuilder.create()

alertDialog.setOnShowListener {

   alertDialog.window?.decorView?.layoutDirection = View.LAYOUT_DIRECTION_RTL
                               }

alertDialog.show()
jafar_aml
  • 309
  • 2
  • 8
1

All you need is to create a style tag in res/values/styles and write :

<style name="alertDialog LayoutDirection">
<item name="android:layoutDirection">rtl</item>

and then add this after alert dialog initializing in your activity :

alertDialog.setView(R.style.alertDialog);

for example :

AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        alertDialog.setMessage("حذف بشه؟")
                .setCancelable(true);
        alertDialog.setPositiveButton("آره", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "yes", Toast.LENGTH_SHORT).show();
            }
        });
        alertDialog.setNegativeButton("نه", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "nooo", Toast.LENGTH_SHORT).show();
            }
        });

        alertDialog.show();
        alertDialog.setView(R.style.alertDialog);
0

For setting layout direction of alert dialog to RTL you can use OnShowListener method. after setting title , message , .... use this method.

dialog = alertdialogbuilder.create();

        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dlg) {
                dialog.getButton(Dialog.BUTTON_POSITIVE).setTextSize(20); // set text size of positive button
                dialog.getButton(Dialog.BUTTON_POSITIVE).setTextColor(Color.RED); set text color of positive button

                dialog.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); // set title and message direction to RTL
            }
        });
        dialog.show();
Hamid
  • 51
  • 7