从代码中更改活动背景

8

我有一个带背景的活动:

<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" />

我该如何通过代码更改背景图片?我目前使用的是mono,但Java示例也会很有帮助。


我选择@imran的答案,因为它最全面。 - xander27
3个回答

18

首先在你的布局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" 

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

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

3

在Java中,我们可以这样做:

给LinearLayout分配一个ID:

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

然后在代码中。
LinearLayout layout=(LinearLayout)findViewById(R.id.parentLayout);

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

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

你需要在 XML 中为你的 LinearLayout 提供 id。


不需要。如果您不想像Vipul的答案那样创建另一个XML文件,您可以在代码中直接操作布局。如果您只需要更改一两个字段,这非常方便。 - Chef Pharaoh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接