Right justify text in AlertDialog
Asked Answered
C

7

24

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.

Chalybite answered 25/5, 2011 at 21:24 Comment(1)
I used this method: #14440038Suet
B
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

Biogen answered 25/5, 2011 at 21:32 Comment(23)
Do I have to define all the theme or is there a base line I can build on? I haven't used themes before.Chalybite
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:<style name="CustomTheme" parent="android:Theme.Light">. Then you would only have to add the items you want changed.Bolyard
I tried doing mydialog = new AlertDialog.Builder(this,R.style.MyDialogTheme) but it claims that the constructor doesn't exists.Chalybite
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.Biogen
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?Chalybite
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.Chalybite
I've added detailed step-by-step instructions to the question. Try it out.Biogen
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.Chalybite
It shouldn't. At least in my project it was centered. Try doing all the steps above in new clean project.Biogen
Same happens in a clean projectChalybite
I cann't reproduce this in my environment. Could you maybe download you project somewhere and post link here?Biogen
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.Chalybite
It might be because of different API Levels. What is your Xperia Android SDK version?Biogen
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.Chalybite
I'm really confused. The last thing you can try is changing your default.properties file: replace target value with target=android-9.Biogen
I am assuming u mean android-7 since that is equivalent to 2.1-update1Chalybite
Yes, change it to android-9. See if it helps. I see different behaviors of dialog with different values.Biogen
Nope - no change. Super-weird.Chalybite
Still stuck here if anyone can help.Chalybite
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.Biogen
Ok - thanks. I'll also upload the mini-project I created and give a link to it.Chalybite
this is not working on the AppCompat them and dialogChaudoin
This no longer works, aapt gives an error: @android:style/DialogWindowTitle is private, and also resource android:style/Theme.Dialog.Alert is private.Vagus
K
32

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();
Kuhns answered 15/5, 2018 at 6:16 Comment(2)
I pretty much like your solution and it changes everything including buttons, but title and message text are not showing, any tips?Demetria
use parent="ThemeOverlay.AppCompat.Dialog.Alert" for setting your theme in custom alert dialog.Bryner
B
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

Biogen answered 25/5, 2011 at 21:32 Comment(23)
Do I have to define all the theme or is there a base line I can build on? I haven't used themes before.Chalybite
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:<style name="CustomTheme" parent="android:Theme.Light">. Then you would only have to add the items you want changed.Bolyard
I tried doing mydialog = new AlertDialog.Builder(this,R.style.MyDialogTheme) but it claims that the constructor doesn't exists.Chalybite
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.Biogen
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?Chalybite
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.Chalybite
I've added detailed step-by-step instructions to the question. Try it out.Biogen
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.Chalybite
It shouldn't. At least in my project it was centered. Try doing all the steps above in new clean project.Biogen
Same happens in a clean projectChalybite
I cann't reproduce this in my environment. Could you maybe download you project somewhere and post link here?Biogen
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.Chalybite
It might be because of different API Levels. What is your Xperia Android SDK version?Biogen
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.Chalybite
I'm really confused. The last thing you can try is changing your default.properties file: replace target value with target=android-9.Biogen
I am assuming u mean android-7 since that is equivalent to 2.1-update1Chalybite
Yes, change it to android-9. See if it helps. I see different behaviors of dialog with different values.Biogen
Nope - no change. Super-weird.Chalybite
Still stuck here if anyone can help.Chalybite
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.Biogen
Ok - thanks. I'll also upload the mini-project I created and give a link to it.Chalybite
this is not working on the AppCompat them and dialogChaudoin
This no longer works, aapt gives an error: @android:style/DialogWindowTitle is private, and also resource android:style/Theme.Dialog.Alert is private.Vagus
L
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.

Lavonnelaw answered 26/9, 2013 at 11:46 Comment(1)
Works great, but I got another problem. Title & text are aligned fine, but buttons aren't. How to get buttons by id?Becalmed
D
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);
}
Doublespace answered 12/7, 2014 at 9:37 Comment(0)
P
1

The kotlinish way :

val alertDialog = alertDialogBuilder.create()

alertDialog.setOnShowListener {

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

alertDialog.show()
Promise answered 6/10, 2019 at 13:5 Comment(0)
O
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);
Olfactory answered 25/1, 2022 at 23:42 Comment(0)
G
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();
Gumption answered 27/2, 2018 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.