简体   繁体   中英

Set color on GradientDrawable not working from Fragment

I have a background drawable like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:bottom="80dp"
      android:id="@+id/card_background">
    <shape>
        <solid android:color="@color/x_card_color_pink"
               android:height="100dp"/>
        <corners
            android:topLeftRadius="10dp"
            android:topRightRadius="10dp"/>
    </shape>
</item>

<item android:top="120dp">
    <shape>
        <solid android:color="@color/white"
            android:height="100dp"/>
        <corners
            android:bottomLeftRadius="10dp"
            android:bottomRightRadius="10dp"/>
    </shape>
</item>

</layer-list>

I want to change the color of card_background . When I set the new color from the activities onCreate it works:

    LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(this, R.drawable.card_background);
    GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.card_background);
    gradientDrawable.setColor(0xFFEBC51B); //Successfully set to yellow from activity

However If try setting it from the fragment that also is showing the background I cant make it change. I want to be able to do this in a clickhandler later on but right now I use the same code in the fragments onCreate :

    LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.card_background);
    GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.card_background);
    gradientDrawable.setColor(0xFF5ABC63); //Fail to set to green from fragment

Im thinking since I am showing the fragment at the same time as I update it I have to refresh it or something? I tried the method invalidateSelf but with no effect.

Any ideas on how I can change the background color from the Fragment?

Oh, I found a solution:

    LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.card_background);
    GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.card_background);
    gradientDrawable.setColor(0xFF5ABC63);

    RelativeLayout layout = (RelativeLayout) rootView.findViewById(R.id.card_layout);
    layout.setBackground(layerDrawable);

If I set the drawable again to my layout it updates the background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM