AlertDialog 标题居中

通过使用AlertDialog.Builder的setCustomTitle方法,可以实现AlertDialog标题的居中显示。具体步骤是创建一个自定义布局,设置标题居中,然后将其设置为AlertDialog的标题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


AlertDialog.Builder alert = new AlertDialog.Builder(this)

                 .setMessage("确定吗?")
                 .setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int id) {
                     }
                 })
                 .setNegativeButton(R.string.back, new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int id) {
                         dialog.cancel();
                     }
                 });


        TextView title = new TextView(this);
        title.setGravity(Gravity.CENTER);
        title.setBackgroundResource(R.drawable.list);
        title.setText("确定");

        alert.setCustomTitle(title);

alert.show();

`AlertDialog.show()`是一个显示对话框的方法,它默认展示的标题通常是左对齐的。如果你想让标题居中,Android并没有直接提供设置标题居中的选项,因为Android的设计倾向于保持组件的一致性和简约。但是,你可以通过自定义`AlertDialog.Builder`并重写其`getTitleView()`方法来实现这个效果。 首先,在你的布局资源文件中创建一个TextView作为标题,并添加到你的自定义视图中: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/title_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?attr/textAppearanceDialogWindowTitle" /> </LinearLayout> ``` 然后,在你的Activity或Fragment中创建并初始化`AlertDialog.Builder`,并将自定义布局作为标题: ```java LayoutInflater inflater = LayoutInflater.from(context); View titleView = inflater.inflate(R.layout.dialog_title_custom, null); AlertDialog.Builder builder = new AlertDialog.Builder(context) .setTitle(new DialogInterface>TitleCreator() { @Override public View getTitleView(DialogInterface dialog, int i) { ((TextView) titleView.findViewById(R.id.title_text_view)).setText(titleText); return titleView; } }); builder.setView(titleView); // 将自定义布局添加到对话框 builder.setCancelable(true); AlertDialog alertDialog = builder.create(); alertDialog.show(); ``` 在这个例子中,`titleText`是你想要显示的标题文本。现在,每次显示对话框时,标题就会居中了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值