Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

background - How to change color of drawable shapes in android

I am developing small android application in which I set drawable resource as background for linear layout. Now what I want to do change background color of linear layout dynamically, but within drawable resource. My code looks like :

//  bcd.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item>        
    <shape>
        <gradient
            android:endColor="#22000000"
            android:startColor="#22000000"
            android:angle="270" />
        <stroke
            android:width="3dp"
            android:color="@color/white" />
        <corners
            android:radius="3dp" />
        <padding
            android:left="10dp"
            android:top="10dp"
            android:right="10dp"
            android:bottom="10dp" />
    </shape>
</item>

<LinearLayout 
android:id="@+id/lin_llt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>

and I set background for linear layout in my activity like this...

parentLayout = (LinearLayout) view.findViewById(R.id.lin_llt);
parentLayout.setBackgroundResource(R.drawable.bcd);

Now what I want to do i want to change color of my drawable resource that mean change color of my linear layout with rounded corner and padding define in drawable..

I tried this in following way

ShapeDrawable bgShape = (ShapeDrawable )parentLayout.getBackground();
bgShape.getPaint().setColor(Color.BLACK);

but its not working for me. any other solution .

So how to do it... Need help... thank you...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change the layout color dynamically

LinearLayout Layout = (LinearLayout) findViewById(R.layout.id);
Layout.setBackgroundColor(Color.parseColor("#ffffff"));

Dynamically set the background color gradient

View layout = findViewById(R.id.mainlayout);

GradientDrawable gd = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM,
        new int[] {0xFF616261,0xFF131313});
gd.setCornerRadius(0f);

layout.setBackgroundDrawable(gd);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...