设置一个活动的背景背景

2023-09-12 08:16:15 作者:画中美人骨

在我活动的onCreate()方法,我抢活动的布局的最外面的LinearLayout。然后我检查一下手机的方位。如果是人像,我设置的LinearLayout为一个图像的背景图像;如果是风景,我设置的LinearLayout的背景图像到另一个图像。

In the onCreate() method of my Activity, I grab the outermost LinearLayout of the Activity's layout. I then check to see what the orientation of the phone is. If it is portrait, I set the background image of the LinearLayout to one image; if it is landscape, I set the background image of the LinearLayout to another image.

一个用户报告说,如果他们打开和关闭他们的硬件键盘的数倍,应用程序会崩溃。由此产生的日志显示一个OutOfMemoryError(位图的大小超过VM预算)错误内心深处的setBackgroundResource从的onCreate()。

A user reported that if they open and close their hardware keyboard several times, the application will crash. The resulting log shows an OutOfMemoryError (bitmap size exceeds VM budget) error deep down in the bowels of setBackgroundResource called from onCreate().

我是不是做错了什么吗?是否有一个内置的方式有Android的处理呢?

Am I doing something wrong here? Is there a built in way to have Android handle this?

如果它是有用的,日志也显示约2打意外简历在崩溃以上。这是用户打开和关闭键盘硬件​​

If it is useful, the log also shows about 2 dozen "unexpected resumes" just above the crash. This is the user opening and closing the hardware keyboard.

推荐答案

重写onConfigurationChange()方法,因为改变布局用这种方法处理的。

Override the onConfigurationChange() method, since the changes in layout are handled with this method.

  @Override
    public void onConfigurationChanged(Configuration newConfig) {
            if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
            {
                //change of background 
            }
            else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT)
            {
                //change the background
            }
                    else
                    { //do nothing, this might apply for the keyboard }


          super.onConfigurationChanged(newConfig);


        }


    }

和添加到您的清单

<activity android:name=".YourActivity"
         android:configChanges="keyboardHidden|orientation"                

                  android:label="@string/app_name">