在 AlertDialog 中右对齐文本

发布于 2024-11-09 21:29:42 字数 68 浏览 6 评论 0原文

是否可以右对齐 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

小嗷兮 2024-11-16 21:29:42

这是一个老问题,但有一个非常简单的解决方案。假设您使用的是 MinSdk 17,您可以将其添加到您的 styles.xml 中:

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

并且在 AlertDialog.Builder 中您只需指定此内容构造函数中的 AlertDialogCustom

new AlertDialog.Builder(this, R.style.AlertDialogCustom)
                    .setTitle("Your title?")
                    .show();

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();
肥爪爪 2024-11-16 21:29:42

据我从 AlertDialogAlertController 您无法访问负责消息的 TextView 标题。

您可以使用反射来访问 AlertDialog 实例中的 mAlert 字段,然后再次使用反射来访问 mAlert< 的 mMessagemTitle 字段/代码>。尽管我不推荐这种方法,因为它依赖于内部结构(将来可能会改变)。


作为另一个(可能更好)的解决方案,您可以通过 AlertDialog 构造函数应用自定义主题。这将允许您右对齐该对话框中的所有 TextView

     protected AlertDialog (Context context, int theme)

这应该是更简单、更稳健的方法。


以下是分步说明:

第 1 步。创建 res/values/styles.xml 文件。其内容如下:

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

第 2 步。创建 RightJustifyAlertDialog.java 文件。其内容如下:

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

第 3 步。 使用 RightJustifyAlertDialog 对话框:

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

第 4 步。 检查结果:

在此处输入图像描述

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

红焚 2024-11-16 21:29:42

如果您想要一种快速且简单的方法来执行此操作,我只需使用 AlertDialog.Builder 创建和修改默认警报。您甚至可以创建一个方便的方法和类,如下所示:

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

当然,您也可以将重力更改为 CENTER 以进行中心对齐,而不是右对齐或默认的左对齐。

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.

可爱咩 2024-11-16 21:29:42

经过一个小时的努力(上面的解决方案对我不起作用),我设法将 AlertDialog 的标题和消息向右对齐,而不覆盖任何样式,只需更改重力和布局参数即可。

在DialogFragment中:

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

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

实际功能:

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

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);
}
阪姬 2024-11-16 21:29:42

kotlinish 方式:

val alertDialog = alertDialogBuilder.create()

alertDialog.setOnShowListener {

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

alertDialog.show()

The kotlinish way :

val alertDialog = alertDialogBuilder.create()

alertDialog.setOnShowListener {

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

alertDialog.show()
━╋う一瞬間旳綻放 2024-11-16 21:29:42

您所需要做的就是在 res/values/styles 中创建一个样式标记并写入:

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

,然后在活动中初始化警报对话框后添加此标记:

alertDialog.setView(R.style.alertDialog);

例如:

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

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);
把时间冻结 2024-11-16 21:29:42

要将警报对话框的布局方向设置为 RTL,您可以使用 OnShowListener 方法。
设置 title , message , .... 之后使用此方法。

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

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文