69

I'm developing an Android application.

How can I center the title for a custom dialog that I'm using?

Ali Khaki
  • 1,184
  • 1
  • 13
  • 24
VansFannel
  • 45,055
  • 107
  • 359
  • 626

13 Answers13

116

Another way that this can be done programatically is using the 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);
SingleWave Games
  • 2,618
  • 9
  • 36
  • 52
59

Just found this post while trying to figure out how to do the same thing. Here's how I did it for anyone else that finds this in the future.

Style xml is as follows:

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

And in my activities onCreateDialog method for the dialog I want styled I create the dialog like this:

Dialog pauseDialog = new Dialog(this, R.style.PauseDialog);
pauseDialog.setTitle(R.string.pause_menu_label);
pauseDialog.setContentView(R.layout.pause_menu);
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
ChrisJD
  • 3,644
  • 1
  • 21
  • 20
  • I tried your suggestion but it does not center the title of the Dialog (HTC Wildfire running with Android 2.2.1)... Any ideas? Because intuitively your solution makes sense :) – Ready4Android Aug 28 '11 at 23:47
  • Sorry, no idea. I've tested it on my Ideos and the emulator with 1.6 and 2.2 with no problems. – ChrisJD Oct 16 '11 at 00:28
  • 1
    there is no "parent="@android:style/DialogWindowTitle"". – Hesam Nov 30 '11 at 10:35
  • Yes there is. It's the 3rd entry in the android styles.xml. You can see it in the SDK in platforms\android-Z\data\res\values\styles.xml (Replace Z with whatever version you have. It's there for 3 through 8 at the very least). – ChrisJD Dec 01 '11 at 02:40
  • 2
    Nice digging. You can actually simplify it to two layers. Sorry for the poor formatting... – ProjectJourneyman Mar 10 '12 at 00:58
  • 1
    This is not correct answer.Correct one done by @LandL Partners – Prakash May 09 '14 at 12:23
  • @ChrisJD how can we apply a light theme? – Apostrofix Jan 13 '16 at 14:50
  • @Prakash the answer you pointed out, is valid for 'AlertDialog' and not for 'Dialog' – Anuj Jun 23 '17 at 09:42
8

You can do it in code as well. Assume you have dialog fragment then add following lines of code.

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

    TextView textView = (TextView) this.getDialog().findViewById(android.R.id.title);
    if(textView != null)
    {
        textView.setGravity(Gravity.CENTER);
    }
}
Hesam
  • 52,260
  • 74
  • 224
  • 365
3

Similar to @LandL Partners solution, but in Kotlin:

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)
Jerry Chong
  • 7,954
  • 4
  • 45
  • 40
2

For your custom DialogFragment you can do this:

@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;
}
2

You can do it programmatically without custom view:

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

Thanks @hesam for the idea. For appcompat layout see Android/sdk/platforms/android-26/data/res/layout/alert_dialog_title_material.xml

soshial
  • 5,906
  • 6
  • 32
  • 40
1

If you don't call AlertDialog.Builder.setIcon() and AlertDialog.Builder.setTitle(), then your custom dialog will not show the built-in/default title View. In this case you are able to add your custom title View:

AlertDialog.Builder.setView(View view)

As soon as it is you who create this View it is possible to implement any type of alignment.

Vit Khudenko
  • 28,288
  • 10
  • 63
  • 91
1
TextView titleView = (TextView) dialog.findViewById(android.R.id.title);
if(titleView != null) {
titleView.setGravity(Gravity.CENTER);
}

See this KodeCenter article on Android Dialog and AlertDialog for more details.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
1
    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);
Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
0

Here's a nasty solution.... Extend AlertDialog.Builder and override all the methods (eg. setText, setTitle, setView, etc) to not set the actual Dialog's text/title/view, but to create a new view within the Dialog's View do everything in there. Then you are free to style everything as you please.

To clarify, as far as the parent class is concerned, the View is set, and nothing else.

As far as your custom extended class is concerned, everything is done within that view.

Steven L
  • 15,304
  • 1
  • 21
  • 16
0

You've got some starting tips here for modifying the title of a dialog: Android - change custom title view at run time Don't know if it can be centered(haven't tried), but if it's a custom View I guess it's very possible.

Community
  • 1
  • 1
Vuk
  • 1,225
  • 12
  • 15
0

Try this:

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

Full code (using 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) {

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

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

helpDialog.show(); 
Vitaly Zinchenko
  • 4,871
  • 5
  • 36
  • 52
0

In Kotlin, you can do it in 1 line

dialog!!.window!!.attributes = dialog!!.window!!.attributes.apply { dimAmount = 0F }
El Sushiboi
  • 428
  • 7
  • 19