Пользовательский диалог на Android: как мне отцентрировать его заголовок? - PullRequest
64 голосов
/ 26 октября 2010

Я занимаюсь разработкой приложения для Android.

Как разместить центр заголовка для настраиваемого диалогового окна, которое я использую?

Ответы [ 12 ]

103 голосов
/ 13 ноября 2012

Другой способ сделать это программно - использовать setCustomTitle ():

// Creating the AlertDialog with a custom xml layout (you can still use the default Android version)
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.viewname, null);
builder.setView(view);

TextView title = new TextView(this);
// You Can Customise your Title here 
title.setText("Custom Centered Title");
title.setBackgroundColor(Color.DKGRAY);
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(20);

builder.setCustomTitle(title);
57 голосов
/ 08 апреля 2011

Только что нашел этот пост, пытаясь понять, как сделать то же самое. Вот как я это сделал для всех, кто найдет это в будущем.

Стиль xml выглядит следующим образом:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <style name="PauseDialog" parent="@android:style/Theme.Dialog">
            <item name="android:windowTitleStyle">@style/PauseDialogTitle</item>
        </style>

        <style name="PauseDialogTitle" parent="@android:style/TextAppearance.DialogWindowTitle">
            <item name="android:gravity">center_horizontal</item>
        </style>
        <style name="DialogWindowTitle">
        <item name="android:maxLines">1</item>
        <item name="android:scrollHorizontally">true</item>
        <item name="android:textAppearance">@android:style/TextAppearance.DialogWindowTitle</item>
        </style>
    </resources>

И в моих действиях метод onCreateDialog для диалога, который я хочу стилизовать, создаю диалог следующим образом:

Dialog pauseDialog = new Dialog(this, R.style.PauseDialog);
pauseDialog.setTitle(R.string.pause_menu_label);
pauseDialog.setContentView(R.layout.pause_menu);
8 голосов
/ 09 октября 2014

Вы можете сделать это и в коде. Предположим, у вас есть фрагмент диалога, затем добавьте следующие строки кода.

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

    TextView textView = (TextView) this.getDialog().findViewById(android.R.id.title);
    if(textView != null)
    {
        textView.setGravity(Gravity.CENTER);
    }
}
2 голосов
/ 14 декабря 2017

Вы можете сделать это программно без пользовательского представления:

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

    TextView textViewVanilla = (TextView) this.getDialog().findViewById(android.R.id.title);
    if(textViewVanilla != null)
    {
        textViewVanilla.setGravity(Gravity.CENTER);
    }
    // support for appcompat v7
    TextView textViewAppcompat = (TextView) this.getDialog().findViewById(android.support.v7.appcompat.R.id.alertTitle);
    if(textViewAppcompat != null)
    {
        textViewAppcompat.setGravity(Gravity.CENTER);
    }
}

Спасибо @ hesam за идею.Макет appcompat см. Android/sdk/platforms/android-26/data/res/layout/alert_dialog_title_material.xml

1 голос
/ 13 апреля 2017
TextView titleView = (TextView) dialog.findViewById(android.R.id.title);
if(titleView != null) {
titleView.setGravity(Gravity.CENTER);
}

Подробнее см. в этой статье KodeCenter об Android Dialog и AlertDialog .

1 голос
/ 24 мая 2016

Для вашего собственного DialogFragment вы можете сделать это:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    final TextView textView = (TextView) dialog.findViewById(android.R.id.title);
    if(textView != null) {
        textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
    }
    return dialog;
}
1 голос
/ 26 октября 2010

Если вы не вызовете AlertDialog.Builder.setIcon() и AlertDialog.Builder.setTitle(), то в вашем пользовательском диалоговом окне не будет отображаться встроенный заголовок / вид по умолчанию. В этом случае вы можете добавить свой собственный заголовок Вид:

AlertDialog.Builder.setView(View view)

Как только вы создадите это представление, вы сможете реализовать любой тип выравнивания.

0 голосов
/ 20 июня 2019

Аналогично решению @LandL Partners, но в Котлине:

val builder = AlertDialog.Builder(this)
val inflater = this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

val view = inflater.inflate(R.layout.viewname, null)
builder.setView(view)
val title = TextView(this)
title.setText("Custom Centered Title")
title.setBackgroundColor(Color.DKGRAY)
title.setPadding(10, 10, 10, 10)
title.setGravity(Gravity.CENTER)
title.setTextColor(Color.WHITE)
title.setTextSize(20)

builder.setCustomTitle(title)
0 голосов
/ 12 июня 2018
    AlertDialog alertDialog = new AlertDialog.Builder(activity)

            .setMessage(message)
            .create();
    alertDialog.setIcon(R.mipmap.ic_launcher_round);

    @SuppressLint("RestrictedApi")
    DialogTitle titleView=new DialogTitle(activity);
    titleView.setText(title);
    titleView.setPaddingRelative(32,32,32,0);
    alertDialog.setCustomTitle(titleView);
0 голосов
/ 23 мая 2017

Попробуйте это:

TextView titleText = (TextView) helpDialog.findViewById(R.id.alertTitle);
if(titleText != null) {
    titleText.setGravity(Gravity.CENTER);
}

Полный код (с использованием android.support.v7.app.AlertDialog):

 AlertDialog.Builder helpDialogBuilder = new AlertDialog.Builder(context)
        .setTitle(/*your title*/)
        .setMessage(/*your message*/)
        .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        /*you can do something here*/

                        dialog.dismiss();
                    }
                })
        .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        /*you can do something here*/

                        dialog.dismiss();
                    }
                });

final AlertDialog helpDialog = helpDialogBuilder.create();

helpDialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialog) {

        <b>TextView titleText = (TextView) helpDialog.findViewById(R.id.alertTitle);
        if(titleText != null) {
            titleText.setGravity(Gravity.CENTER);
        }</b>

        TextView messageText = (TextView) helpDialog.findViewById(android.R.id.message);
        if(messageText != null) {
            messageText.setGravity(Gravity.CENTER);
        }
    }
});

helpDialog.show(); 
...