如何在android中水平居中设置对话框的标题

时间:2016-12-16 18:42:20

标签: android android-dialogfragment android-dialog

这是我在android中显示自定义对话框的代码。

private void showCouponCodeDialog() {

    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialoge_apply_coupon);
    dialog.setTitle(R.string.apply_coupon);

    final ProgressBar progressBar =(ProgressBar) dialog.findViewById(R.id.progressBar);

    Button btnApplyCoupon = (Button) dialog.findViewById(R.id.btnApplyCoupon);
    btnApplyCoupon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
        }
    });
    dialog.show();
}

如何在水平居中设置对话框的标题?

1 个答案:

答案 0 :(得分:0)

设置自定义样式,根据需要将重力设置为特定的

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

将样式指定给对话框

Dialog pauseDialog = new Dialog(this, R.style.PauseDialog);

正常做其他事情

或手动设置自定义标题

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