您的位置:首页 > 移动开发 > Android开发

[Android界面] 屏幕方向改变资源处理问题 [

2015-01-20 16:27 190 查看
http://www.eoeandroid.com/thread-105596-1-1.html
当android手机屏幕方向改变等想关系统设置改变后,会导致当前activity销毁并重建,这是需要处理界面中的布局,资源等,以便给用户更好的体验

下面文档中的例子,当前activity从网络上下载图片并显示,如果在屏幕方向改变后,activity销毁并重建,这是新的activity会重新下载上次的图片,这个用户体验是很不好的,如何解决呢

处理activity的configuration changes相关的方法 在这些方法中对图片资源暂时缓存

方法一:Object onRetainNonConfigurationInstance()

          Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration.   

configuration change时调用 可以在这里对资源进行保存 并返回

方法二:getLastNonConfigurationInstance()  

               Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance(). This will be available from the initial onCreate(Bundle) and onStart() calls to the
new instance, allowing you to extract any useful dynamic state from the previous instance.

           Note that the data you retrieve here should only be used as an optimization for handling configuration changes. You should             always be able to handle getting a null pointer back, and an activity must still be able to restore itself to its  previous
state(throughthe  normal onSaveInstanceState(Bundle) mechanism) even if this function returns null        

   

          在oncreate() 或onstart()中手动调用,返回object 也就是onRetainNonConfigurationInstance()返回的对象,返回的数据只作为configuration changes的优化处理

               如果返回的为Null,说明activity没有销毁、重建,这时需要去下载图片资源

Be very careful with the object you pass through onRetainNonConfigurationChange(), though. If the object you pass is for some reason tied to the Activity/Context, you will leak all the views and resources of the activity. This means you should never pass a
View, a Drawable, an Adapter, etc. Photostream for instance extracts the bitmaps from the drawables and pass the bitmaps only, not the drawables. Finally, remember that onRetainNonConfigurationChange() should be used only to retain data that is expensive to
load. Otherwise, keep it simple and let Android do everything.

如果 onRetainNonConfigurationChange()  返回的对象由于一些原因与activity或context绑定,会导致内存泄漏。 不要传递drawable对象,最后传递bitmap              

--------------------------------------------------------------------------------------------------------------------------------------------------  

解决办法二: 

onSaveInstanceState(Bundle outState)     在activity销毁时调用 这里也可以保存信息

@Override

      protected void onSaveInstanceState(Bundle outState) {

            // TODO Auto-generated method stub

            super.onSaveInstanceState(outState);

      }

  

onRestoreInstanceState(Bundle savedInstanceState)  onstart()后调用  获取保存的信息

      @Override

      protected void onRestoreInstanceState(Bundle savedInstanceState) {

            // TODO Auto-generated method stub

            super.onRestoreInstanceState(savedInstanceState);

      }

               

以下是官方文档

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Android is designed to run efficiently on a wide array of devices, with very different hardware configurations. Some devices, like the T-Mobile G1, can change their hardware configuration at runtime. For instance, when you open the keyboard, the screen change
from the portrait orientation to the landscape orientation.

Using the alternate resources framework

The platform's support for loading orientation-specific resources at run time is based on the alternate resources framework.

Providing orientation-specific resources is an important part of developing your app. If you are not familiar with resource directory qualifiers or how the platform uses them, please read Alternate Resources.

To make Android app development easier, the Android system automatically handles configuration change events and restarts the current activity with the new configuration. This is the default behavior that lets you declare resources like layouts and drawables
based on the orientation, screen size, locale, etc.

While this behavior is really powerful, since your application adapts automatically to the device's configuration at runtime, it is sometimes confusing for new Android developers, who wonder why their activity is destroyed and recreated.

Facing this "issue," some developers choose to handle configuration changes themselves which is, in general, a short-term solution that will only complicate their lives later. On the other hand, the system's automatic resource handling is a very efficient and
easy way to adapt an application's user interface to various devices and devices configurations. It sometimes comes at a price, though.

When your application displays a lot of data, or data that is expensive to fetch, the automatic destruction/creation of the activities can be lead to a painful user experience. Take the example of Photostream, a simple Flickr browsing application. After you
launch the application and choose a Flickr account, the application downloads a set of 6 photos (on a T-Mobile G1) from the Flickr servers and displays them on screen. To improve the user experience, the application uses slightly different layouts and drawables
in portrait and landscape modes and this is what the result looks like:

Photostream lets Android take care of the configuration change when the screen is rotated. However, can you imagine how painful it would be for the user to see all the images being downloaded again? The obvious solution to this problem is to temporarily cache
the images. They could be cached on the SD card (if there's one), in the Application object, in a static field, etc. None of these techniques is adapted to the current situation: why should we bother caching the images when the screen is not rotated? Fortunately
for us, Android offers a great API exactly for that purpose.

The Activity class has a special method called onRetainNonConfigurationInstance(). This method can be used to pass an arbitrary object your future self and Android is smart enough to call this method only when needed. In the case of Photostream, the application
used this method to pass the downloaded images to the future activity on orientation change. The implementation can be summarized like so:

@Override

public Object onRetainNonConfigurationInstance() {

    final LoadedPhoto[] list = new LoadedPhoto[numberOfPhotos];

    keepPhotos(list);

    return list;

}

In the new activity, in onCreate(), all you have to do to get your object back is to call getLastNonConfigurationInstance(). In Photostream, this method is invoked and if the returned value is not null, the grid is loaded with the list of photos from the previous
activity:

private void loadPhotos() {

    final Object data = getLastNonConfigurationInstance();

    

    // The activity is starting for the first time, load the photos from Flickr

    if (data == null) {

        mTask = new GetPhotoListTask().execute(mCurrentPage);

    } else {

        // The activity was destroyed/created automatically, populate the grid

        // of photos with the images loaded by the previous activity

        final LoadedPhoto[] photos = (LoadedPhoto[]) data;

        for (LoadedPhoto photo : photos) {

            addPhoto(photo);

        }

    }

}
ActivityViewdrawableResource布局
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: