单击按钮更改背景图片 android 应用程序开发

Changing background image on button click android app development

我正在尝试更改 activity 的背景图片 单击按钮,但无法这样做。你们能告诉我我该怎么做吗?

Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try
        {
            Activity activity = Selection.this;
            //Drawable db = Drawable..createFromPath(R.drawable.love1);

            // The below line gives error because setbackgroundImage 
            // is supposed to take a drawable object as an argument. 
            // Now what to do?                                  
            activity.findViewById(android.R.id.content)
            .setBackground(Drawable.createFromPath("res/love1.jpg"));

            // What to do to correct the above line?

            mySong = MediaPlayer.create(Selection.this, R.raw.song1);
            mySong.start();
        }
        catch(Exception ee){
            TextView tv = (TextView) findViewById(R.id.textView1);
            tv.setText(ee.getMessage());
        }
    }
});

我尝试 Color.RED 使用 setBackgroundColor 但这也不起作用。 PS:我没有更改 xml 文件中的任何内容来完成此操作。

我认为最简单的方法是在 xml 文件中为 activity 使用布局。例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/linearLayoutID" 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/background_img1" >

然后在需要时从 Activity 更改它,例如单击按钮后:

 LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linearLayoutID);
 mLinearLayout.setBackgroundResource(R.drawable.background_img2);

Change setBackground(Drawable) to setBackgroundResource(R.drawable.filename)

线性布局 mLinearLayout = (LinearLayout) findViewById(R.id.LayoutID); mLinearLayout.setBackgroundResource(R.drawable.image_name);