Android-用style修改AlertDialog按钮文字颜色

android系统为开发者提供了AlertDialog,用于快捷创建dialog。

alert_dialog

用Builder模式创建,可以轻松设置title,message,取消,确定按钮点击事件等。但是本人实际项目用的比较少,因为跟UI设计的样式不太一样,按钮文字颜色不太好修改。经过一番查找,找到了修改按钮文字颜色的方法。

AlertDialog最底层的构造方法:
/**
     * Construct an AlertDialog that uses an explicit theme.  The actual style
     * that an AlertDialog uses is a private implementation, however you can
     * here supply either the name of an attribute in the theme from which
     * to get the dialog's style (such as {@link R.attr#alertDialogTheme}.
     */
    protected AlertDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, resolveDialogTheme(context, themeResId));
        mAlert = new AlertController(getContext(), this, getWindow());
    }
AlertController控制的布局。
public AlertController(Context context, AppCompatDialog di, Window window) {
        mContext = context;
        mDialog = di;
        mWindow = window;
        mHandler = new ButtonHandler(di);

        final TypedArray a = context.obtainStyledAttributes(null, R.styleable.AlertDialog,
                R.attr.alertDialogStyle, 0);

        mAlertDialogLayout = a.getResourceId(R.styleable.AlertDialog_android_layout, 0);
        mButtonPanelSideLayout = a.getResourceId(R.styleable.AlertDialog_buttonPanelSideLayout, 0);

        mListLayout = a.getResourceId(R.styleable.AlertDialog_listLayout, 0);
        mMultiChoiceItemLayout = a.getResourceId(R.styleable.AlertDialog_multiChoiceItemLayout, 0);
        mSingleChoiceItemLayout = a
                .getResourceId(R.styleable.AlertDialog_singleChoiceItemLayout, 0);
        mListItemLayout = a.getResourceId(R.styleable.AlertDialog_listItemLayout, 0);
        mShowTitle = a.getBoolean(R.styleable.AlertDialog_showTitle, true);

        a.recycle();

        /* We use a custom title so never request a window title */
        di.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    }
可以看到各种自定义属性,是用R.styleable.AlertDialog获取的。打开android系统values搜索AlertDialog:

这里写图片描述

可以看到有一个style的属性,与AlertDialog的R.styleable.AlertDialog自定义属性是对应的,说明可以控制UI样式。
		<item name="android:layout">@layout/abc_alert_dialog_material</item>
        <item name="listLayout">@layout/abc_select_dialog_material</item>
        <item name="listItemLayout">@layout/select_dialog_item_material</item>
        <item name="multiChoiceItemLayout">@layout/select_dialog_multichoice_material</item>
        <item name="singleChoiceItemLayout">@layout/select_dialog_singlechoice_material</item>
打开@layout/abc_alert_dialog_material:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2015 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<android.support.v7.widget.AlertDialogLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parentPanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="start|left|top"
    android:orientation="vertical">

    <include layout="@layout/abc_alert_dialog_title_material"/>

    <FrameLayout
        android:id="@+id/contentPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="48dp">

        <View android:id="@+id/scrollIndicatorUp"
              android:layout_width="match_parent"
              android:layout_height="1dp"
              android:layout_gravity="top"
              android:background="?attr/colorControlHighlight"
              android:visibility="gone"/>

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <android.support.v4.widget.Space
                    android:id="@+id/textSpacerNoTitle"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/abc_dialog_padding_top_material"
                    android:visibility="gone"/>

                <TextView
                    android:id="@android:id/message"
                    style="@style/TextAppearance.AppCompat.Subhead"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingLeft="?attr/dialogPreferredPadding"
                    android:paddingRight="?attr/dialogPreferredPadding"/>

                <android.support.v4.widget.Space
                    android:id="@+id/textSpacerNoButtons"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/abc_dialog_padding_top_material"
                    android:visibility="gone"/>
            </LinearLayout>
        </android.support.v4.widget.NestedScrollView>

        <View android:id="@+id/scrollIndicatorDown"
              android:layout_width="match_parent"
              android:layout_height="1dp"
              android:layout_gravity="bottom"
              android:background="?attr/colorControlHighlight"
              android:visibility="gone"/>

    </FrameLayout>

    <FrameLayout
        android:id="@+id/customPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="48dp">

        <FrameLayout
            android:id="@+id/custom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </FrameLayout>

    <include layout="@layout/abc_alert_dialog_button_bar_material"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"/>

</android.support.v7.widget.AlertDialogLayout>
最下面include了一个layout点进去:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2014 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/buttonPanel"
            style="?attr/buttonBarStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:scrollIndicators="top|bottom">

    <android.support.v7.widget.ButtonBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layoutDirection="locale"
        android:orientation="horizontal"
        android:paddingBottom="4dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="4dp">

        <Button
            android:id="@android:id/button3"
            style="?attr/buttonBarNeutralButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <android.support.v4.widget.Space
            android:id="@+id/spacer"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:visibility="invisible"/>

        <Button
            android:id="@android:id/button2"
            style="?attr/buttonBarNegativeButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <Button
            android:id="@android:id/button1"
            style="?attr/buttonBarPositiveButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </android.support.v7.widget.ButtonBarLayout>

</ScrollView>
button2和button1就是AlertDialog的取消和确定按钮。样式分别用了buttonBarNegativeButtonStyle和buttonBarPositiveButtonStyle两个style。搜索这两个style发现:
<item name="buttonBarStyle">@style/Widget.AppCompat.ButtonBar</item>
	<item name="buttonBarButtonStyle">@style/Widget.AppCompat.Button.ButtonBar.AlertDialog</item>
        <item name="buttonBarPositiveButtonStyle">?attr/buttonBarButtonStyle</item>
        <item name="buttonBarNegativeButtonStyle">?attr/buttonBarButtonStyle</item>
        <item name="buttonBarNeutralButtonStyle">?attr/buttonBarButtonStyle</item>
那么我们只需要在自己的主题重新定buttonBarNegativeButtonStyle和buttonBarPositiveButtonStyle两个style就可以修改按钮样式了。
看下效果:

这里写图片描述

我修改的样式:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="buttonBarPositiveButtonStyle">@style/positiveBtnStyle</item>
        <item name="buttonBarNegativeButtonStyle">@style/negativeBtnstyle</item>

    </style>

    <!--确定按钮样式-->
    <style name="positiveBtnStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
        <item name="android:textColor">#0000ff</item>
    </style>

    <!--取消按钮样式-->
    <style name="negativeBtnstyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
        <item name="android:textColor">#999999</item>
    </style>


</resources>


AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("你确定要把这5块钱捐给红十字会吗?")
                .setTitle("标题")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定",null)
                .show();

修改框架层的AlertDialog的确认和取消按钮文字颜色,你可以尝试以下步骤: 1. 创建一个自定义的AlertDialog主题,在其中设置按钮文字颜色。在你应用的 `res/values/styles.xml` 文件中添加以下代码: ```xml <style name="CustomAlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="android:buttonBarButtonStyle">@style/CustomButtonBarButtonStyle</item> </style> <style name="CustomButtonBarButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog"> <item name="android:textColor">@color/custom_button_text_color</item> </style> ``` 2. 在你的 `res/values/colors.xml` 文件中定义你想要的自定义按钮文字颜色: ```xml <color name="custom_button_text_color">#FF0000</color> ``` 3. 在使用AlertDialog的地方,将主题设置为你自定义的主题。例如,在Activity中使用: ```java AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.CustomAlertDialogTheme)); builder.setTitle("Title") .setMessage("Message") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // 点击确认按钮的逻辑 } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // 点击取消按钮的逻辑 } }); AlertDialog dialog = builder.create(); dialog.show(); ``` 通过以上步骤,你可以自定义AlertDialog的确认和取消按钮文字颜色。记得将 `custom_button_text_color` 替换为你想要的颜色值。希望这能帮到你!
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值