Right justify text in AlertDialog

给你一囗甜甜゛ 提交于 2019-12-17 16:34:46

问题


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.


回答1:


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:




回答2:


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.




回答3:


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="Theme.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();



回答4:


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



回答5:


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



回答6:


The kotlinish way :

val alertDialog = alertDialogBuilder.create()

alertDialog.setOnShowListener {

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

alertDialog.show()


来源:https://stackoverflow.com/questions/6131133/right-justify-text-in-alertdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!