Dalija Prasnikar
Dalija Prasnikar

Reputation: 28530

How to automatically apply material primary and accent colors to dialog

I have custom theme with changed primary and accent colors. But AlertDialog is not picking up those colors automatically when I create dialog using:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

This is what I get - dialog with default colors:

Default theme

And this is what I would like to have - dialog with custom colors:

enter image description here

I can create custom AlertDialog theme and apply it during AlertDialog creation:

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppTheme_Dialog);

I would like to skip calling constructor with theme parameter.

Is there a way to force custom colors on all themes without deriving them in styles, including AlertDialog base theme?

Minimup API level I have to support is 15.


My activity code

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dialog();
    }

    public void dialog()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Dialog");
        builder.setMessage("Lorem ipsum dolor ...");
        builder.setPositiveButton("OK", null);
        builder.setNegativeButton("Cancel", null);
        builder.show();
    }
}

My customized style

<resources>
    <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>
    </style>

    <style name="AppTheme.Dialog" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

My colors

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

Upvotes: 1

Views: 1039

Answers (1)

Shirish Kadam
Shirish Kadam

Reputation: 747

Add this in your the App theme:

<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- your style -->
<item name="alertDialogTheme">@style/AppTheme.Dialog</item>

And then,

import android.support.v7.app.AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);

Upvotes: 5

Related Questions