5

I have implemented the dialog in my app. But the title in the dialog by default in the left side. How can I make the dialog title in the center?

Here is my code

final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.contact_query);
dialog.setTitle("Query Form");
Vivek Kumar
  • 61
  • 1
  • 3
  • 4
    Possible duplicate of [Custom dialog on Android: How can I center its title?](http://stackoverflow.com/questions/4025605/custom-dialog-on-android-how-can-i-center-its-title) – Harshad Pansuriya Sep 03 '16 at 07:19

3 Answers3

8

You can try this:

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

*Try this one *

    Dialog dialog = new Dialog(this);

    dialog.setContentView(R.layout.yourlayout);

    TextView titleView = (TextView)dialog.findViewById(android.R.id.title);

    titleView.setGravity(Gravity.CENTER);

For more information http://kodecenter.com/article?id=2390ec63-63d7-4534-a76f-cc3b10497a2c

AAli
  • 49
  • 3
0

If you use an AlertDialog Builder, create a layout for your dialog title (in which you can center the text for example), inflate it and give it to the builder. Like so :

res/layout/dialog_title.xml :

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/colorPrimaryDark_rc"
  android:textSize="22sp"
  android:gravity="center"
  android:textColor="@color/textColorPrimaryDark"
  android:padding="10dp"/>

Java:

public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(act);

    LayoutInflater layoutInflater = act.getLayoutInflater();
    View customView = layoutInflater.inflate(R.layout.l_df_episode_details, null);
    alertDialogBuilder.setView(customView);

    TextView tv = (TextView) layoutInflater.inflate(R.layout.dialog_title, null);
    tv.setText("YOUR TITLE");
    alertDialogBuilder.setCustomTitle(tv); 

    ......

    alertDialog = alertDialogBuilder.create();
    return alertDialog;
}
u2gilles
  • 6,888
  • 7
  • 51
  • 75