TJBlack31
TJBlack31

Reputation: 785

Android DialogFragment - How to change color of dialog fragment with rounded corners programmatically

looked into this quite a bit, but my experience with Layer list is still subpar. Here is my xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="10dip"/>
        <padding
            android:bottom="2dip"
            android:left="8dip"
            android:right="8dip"
            android:top="2dip"/>
    </shape>
</item>

<item
    android:id="@+id/dialog_bg">
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid android:color="#FFFFFF"/>
        <stroke
            android:width="16dip"
            android:color="#FFFFFF"/>

        <padding
            android:bottom="2dip"
            android:left="8dip"
            android:right="8dip"
            android:top="2dip"/>
    </shape>
</item>
</layer-list>

Do I have the right idea as to how to do this?

I'm wanting to use this java method:

getDialog().getWindow().setBackgroundDrawableResource(R.drawable.rounded_corners_dialog);

But how would I go about changing the color of it, later on in the code?

Thanks,

T

Upvotes: 1

Views: 526

Answers (1)

sagar suri
sagar suri

Reputation: 4731

You can make CardView as the parent container of the layout of your custom DialogFragment. Here is a quick example:

custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:cardCornerRadius="8dp"
    app:cardElevation="10dp"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
        //Put all your views here

    </LinearLayout>
</android.support.v7.widget.CardView>

Now in your class that extends DialogFragment override onCreateDialog like this:

@NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }

Now later on you can make a rounded corner and you can change the background colour of the CardView. Try it :)

Upvotes: 4

Related Questions