android - 更改按钮上的背景图像单击android应用程序开发

标签 android android-intent android-fragments android-activity

我正在尝试更改 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());
        }
    }
});

我尝试使用 setBackgroundColor 对 Color.RED 进行设置,但这也不起作用。 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);

关于android - 更改按钮上的背景图像单击android应用程序开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735869/

相关文章:

android - 从 Smartwatch Android Wear 获取数据到智能手机

android - 从 Intent 中获取多个广播?

android - 如何在 ListView 单元格中使用 Fragment?

android - 意式 Espresso 与我的 ACTION_SEND Intent 不匹配

Android Intent 清除顶部不起作用

android - 恢复后 map fragment 为黑色

android - fragment 中奇怪的 onPause()、onResume() 行为

android - 互联网连接丢失时不停止读取 Inputstream

java - 通过 Android 应用程序注册教师?

android - 运行时权限 : Failure delivering result ResultInfo{who=@android:requestPermissions:, request=123, result=0, data=null} 到 Activity