按钮单击更改背景图像

use*_*788 0 java eclipse android button

我正在使用eclipse来编写我的Android应用程序,我想知道如何在单击按钮时更改MainActivity的背景图像.我有img1.png和img2.png.目前使用以下xml代码在img1.png上设置背景:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/img1"
    tools:context=".MainActivity" >
<Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="46dp"
        android:layout_marginTop="55dp"
        android:background="@android:color/transparent"
        android:text="" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我只是不确定我将使用什么java代码来更改btn1 click上的背景图像.

Lal*_*Lal 5

此代码可用于以编程方式设置背景图像

RelativeLayout layout =(RelativeLayout)findViewById(R.id.relativelayout);
layout.setBackgroundResource(R.drawable.img1);
Run Code Online (Sandbox Code Playgroud)