在GradientDrawable上设置颜色不能从片段

时间:2015-12-23 03:33:37

标签: java android android-fragments

我有这样的背景:

<?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>

我想更改card_background的颜色。当我从活动onCreate设置新颜色时,它可以工作:

    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

但是如果尝试从也显示背景的片段设置它,我就无法改变它。我希望以后能够在点击处理程序中执行此操作,但现在我在片段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

我想,因为我在更新它的同时显示片段,我必须刷新它或什么?我尝试了invalidateSelf方法但没有效果。

关于如何从Fragment中更改背景颜色的任何想法?

1 个答案:

答案 0 :(得分:2)

哦,我找到了解决方案:

    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);

如果我再次将drawable设置为我的布局,则会更新背景。