Wednesday, February 04, 2026

Customizing a Preference Alert Dialog for an EditTextPreference in Android

 In your themes.xml, add the following:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

  <style name="Theme.Your_Theme" parent="Theme.MaterialComponents.DayNight.NoActionBar" android:forceDarkAllowed="true">

[...]

    <item name="alertDialogTheme">@style/YourAlertDialogTheme</item>
  </style>

 </resources>

In the styles.xml, add the style for the dialog itself:

 <style name="YourAlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
   <!-- Changes the dialog background color -->
   <item name="android:windowBackground">@color/light_grey</item>
   <!-- Changes the title and message text color -->
   <item name="android:textColorPrimary">@color/alert_dialog_button_txt</item>
   <!-- If using Material Components, use this for buttons -->
   <!--<item name="buttonBarPositiveButtonStyle">@style/Widget.MaterialComponents.Button.TextButton</item>-->
   <item name="buttonBarPositiveButtonStyle">@style/Widget.Your.Button.TextButton</item>
   <item name="buttonBarNegativeButtonStyle">@style/Widget.Your.Button.TextButton</item>
 </style>

 <style name="Widget.Your.Button.TextButton" parent="Widget.MaterialComponents.Button.TextButton">
   <!-- Changes the text and icon color -->
   <item name="android:textColor">@color/alert_dialog_button_txt</item>
   <!--<item name="iconTint">@color/red_status</item>-->
   <!-- Changes the click ripple color -->
   <!--<item name="rippleColor">@color/green_dark</item>-->
 </style>

In your your_preferences.xml, add:

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">

  <EditTextPreference
    app:key="pk_quality_threshold"
    app:title="@string/title_quality_threshold"
    app:dialogTitle="@string/title_quality_threshold"
    app:summary="@string/leak_quality_threshold_summary"
    app:defaultValue="40"
    app:dialogLayout="@layout/pref_edittext" />

Then define the custom layout for the EditTextPreference to change the color of the edit text background, text and cursor:

pref_edittext.xml

<?xml version="1.0" encoding="utf-8"?>

<!-- Used in ui_preferences.xml -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp"
    android:orientation="vertical">

    <!-- If you use: android:textCursorDrawable="@null"
    the cursor will automatically inherit the color defined in
    the android:textColor property -->
    <EditText
        android:id="@android:id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/alert_dialog_button_txt"
        android:background="@color/white"
        android:textCursorDrawable="@null"
        android:padding="8dp" />

</LinearLayout>

Done!
 

No comments: