开发者

how to change the xml background in android dynamically?

I am need a logic to change the xml background programatically instead of giving the backgroung color from xml file. here i used setContentView(R.layout.main); to show the xml file in application. But i need to change the background color of m开发者_如何学编程ain.xml file in java code.


Following is the example that shows how can you make it. Here i have taken LinearLayout as the root node of xml file. In java code i have shown that how to set white background. I think this code will help you.

xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
-----
-----
</LinearLayout>

java code

LinearLayout root=(LinearLayout)findViewById(R.id.root);
root.setBackgroundColor(Color.WHITE);

It can also possible to set color using Hex code as shown below,

root.setBackgroundColor(Color.parseColor("#ffffff"));

Even you can set drawable also,

root.setBackgroundResource(R.drawable.bg_image);


Here is how you can do that,

 mLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);
 mLayout.setBackgroundColor(Color.BLUE);

Here mLayout is your parent RelativeLayout.


get the instance of the root layout of your xml and set it's background color from your code as you wish as many times you want but do all this in your UI thread..


GradientDrawable sd = (GradientDrawable)this.getResources().getDrawable(R.drawable.roundbordertry); sd.setColor(Color.rgb(5, 5,5)); newHeadView.setBackgroundDrawable(sd);

////////////////////////////////////////////////////////// roundbordertry is the xml file. newHeadView is a linearlayout.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜