Android 从代码更改活动背景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11115158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:03:03  来源:igfitidea点击:

Change activity background from code

androiduser-interfacexamarin.androidandroid-activity

提问by xander27

I have an activity with a background:

我有一个有背景的活动:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px"
android:background="@drawable/background_fingerboard" />

How can I change background image from code? I actually use mono, but Java samples will also be helpful.

如何从代码更改背景图像?我实际上使用单声道,但 Java 示例也会有所帮助。

回答by ρяσ?ρ?я K

first add LinearLayout id as in your layout xml:

首先在您的布局 xml 中添加 LinearLayout id:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/linearLayoutid" 
android:minWidth="25px"
android:minHeight="25px"
android:background="@drawable/background_fingerboard" 

and in code part set background as::

并在代码部分将背景设置为:

LinearLayout  linearLayout = (LinearLayout) findViewById(R.id.linearLayoutid);
 linearLayout.setBackgroundResource(R.drawable.background_fingerboard);

回答by Vipul Shah

In java we do like this

在java中我们这样做

Give id to LinearLayout

将 id 赋予 LinearLayout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id=@+id/parentLayout  

Then in code

然后在代码中

LinearLayout layout=(LinearLayout)findViewById(R.id.parentLayout);

layout.setBackgroundColor(Color.BLUE);  Or
layout.setBackgroundDrawable(d); Or
layout.setBackgroundResource(resid);

回答by Dheeresh Singh

LinearLayout  vi = (LinearLayout ) findViewById(<id>)
vi.setBackgroundResource(R.drawable.<id2>);

you need to provide the id to your LinearLayout in XML as well....

您还需要在 XML 中为您的 LinearLayout 提供 id....