AlertDialog更改正按钮颜色

L.M*_*eng 5 android material android-alertdialog

在此输入图像描述

我想改变正面按钮的颜色Alertdialog,这是我在下面做的:

// style.xml

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:buttonBarPositiveButtonStyle">@style/positive</item>
</style>

<style name="positive">
    <item name="android:textColor">@color/accent</item>
</style>
Run Code Online (Sandbox Code Playgroud)

我使用的风格是:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogCustom);
Run Code Online (Sandbox Code Playgroud)

但我正在做的不起作用,我只是想改变正面的按钮颜色.我不想在java代码中更改按钮的颜色.

提前致谢 :-)

Edit-1 Alertdialog布局xml

<android.support.v7.internal.widget.ButtonBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/buttonPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="locale"
android:orientation="horizontal"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="4dp"
android:paddingBottom="4dp"
android:gravity="bottom"
app:allowStacking="@bool/abc_allow_stacked_button_bar"
style="?attr/buttonBarStyle">

<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" />
Run Code Online (Sandbox Code Playgroud)

L.M*_*eng 7

注意:不推荐使用该解决方案,因为这实际上是一个hacky解决方案.它不遵循Android设计,不应该使用.我通过java更改正面按钮颜色.感谢@Divers指出这一点.

styles.xml

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="buttonBarPositiveButtonStyle">@style/positive</item>
</style>

<style name="positive">
    <item name="android:textColor">@color/accent</item>
</style>
Run Code Online (Sandbox Code Playgroud)

用法

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogCustom);
Run Code Online (Sandbox Code Playgroud)

也许这里有一点你应该注意,buttonBarPositiveButtonStyle而不是android: buttonBarPositiveButtonStyle.


O_o*_*O_o 5

builder.setOnShowListener( new OnShowListener() {
  @Override
  public void onShow(DialogInterface arg0) {
       builder.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(COLOR_YOU_WANT);
  }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!干杯!


Div*_*ers 0

没有办法通过样式来做到这一点,因为从 UI 的角度来看,通常这是错误的。如果你想这样做,只需通过 java 即可。