Возможно ли правое выравнивание текста в заголовке и сообщении AlertDialog?
Я показываю еврейские сообщения, но они отображаются влево.
Возможно ли правое выравнивание текста в заголовке и сообщении AlertDialog?
Я показываю еврейские сообщения, но они отображаются влево.
Насколько я могу видеть из кода AlertDialog
и AlertController
вы не можете получить доступ к TextView
, ответственному за сообщение и заголовок.
Вы можете использовать отражение для достижения поля mAlert
в экземпляре AlertDialog, а затем снова использовать отражение для доступа к полям mMessage
и mTitle
mAlert
. Хотя я бы не рекомендовал этот подход, поскольку он полагался на внутренности (которые могут измениться в будущем).
В качестве другого (и, вероятно, гораздо лучшего) решения вы можете применить настраиваемую тему через конструктор 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. Проверьте результаты:
Если вам нужен быстрый и простой способ сделать это, я просто создам и изменю предупреждение по умолчанию, используя 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 для выравнивания по центру вместо правого или по умолчанию слева.
Это старый вопрос, но есть очень простое решение. Предполагая, что вы используете MinSdk 17
, вы можете добавить это в свой styles.xml
:
<style name="AlertDialogCustom" parent="Theme.AppCompat.Dialog.Alert">
<item name="android:layoutDirection">rtl</item>
</style>
А в AlertDialog.Builder
вам просто нужно указать этот AlertDialogCustom
в конструкторе:
new AlertDialog.Builder(this, R.style.AlertDialogCustom)
.setTitle("Your title?")
.show();
После борьбы с этим в течение часа (решения выше не работали для меня) мне удалось выровнять заголовок и сообщение AlertDialog вправо, без переопределения каких-либо стилей, просто изменив параметры гравитации и макета.
В диалоговом режиме:
@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 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);
}
Для установки направления расположения диалогового окна предупреждения в RTL вы можете использовать метод OnShowListener. после установки название, сообщение,.... использование этот способ.
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();
Котлинский путь:
val alertDialog = alertDialogBuilder.create()
alertDialog.setOnShowListener {
alertDialog.window?.decorView?.layoutDirection = View.LAYOUT_DIRECTION_RTL
}
alertDialog.show()