How to center the title in the dialog?

2019-05-07 10:19发布

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

3条回答
太酷不给撩
2楼-- · 2019-05-07 11:08

*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

查看更多
Animai°情兽
3楼-- · 2019-05-07 11:08

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;
}
查看更多
可以哭但决不认输i
4楼-- · 2019-05-07 11:20

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);
查看更多
登录 后发表回答