Change shape solid color at runtime inside Drawable xml used as background

孤街浪徒 提交于 2019-11-26 11:01:40

问题


I\'ve a Drawable xml file (background.xml):

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

    <item android:id=\"@+id/shape_id\">
        <shape android:shape=\"rectangle\">
            <solid android:color=\"#ffefefef\" /> 
        </shape>
    </item>

</layer-list>

used by a LinearLayout:

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"
    android:background=\"@drawable/background\"
    android:id=\"@+id/layout_id\"
    >

Now i need to change the shape shape_id solid color at runtime based on some conditions. How to do this?


回答1:


Found by me:

    View v = findViewById(R.id.layout_id);

    LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();
    final GradientDrawable shape = (GradientDrawable)   bgDrawable.findDrawableByLayerId(R.id.shape_id);
    shape.setColor(----);


来源:https://stackoverflow.com/questions/16636412/change-shape-solid-color-at-runtime-inside-drawable-xml-used-as-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!