由于横竖屏切换时Activity会Destroy,又重新创建,导致得重新加载需要的数据。解决这种是在onRestoreNonConfigrationInstance() 方法里保持需要的对象,在横竖屏切换时这个方法会调用,等到Activity重新创建后,通过getLastNonConfigrationInstance()方法取得Object。
- public class Android_testActivity extends Activity {
- /** Called when the activity is first created. */
- TextView textView;
- Drawable drawable;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textView = (TextView)findViewById(R.id.text);
- drawable = (Drawable)getLastNonConfigurationInstance();
- if (drawable == null) {
- drawable = getResources().getDrawable(R.drawable.icon);
- Log.e("Android_test", "drawable is null");
- }
- textView.setBackgroundDrawable(drawable);
- }
- @Override
- public Object onRetainNonConfigurationInstance() {
- // TODO Auto-generated method stub
- return drawable;
- }
- public void onDestroy(){
- super.onDestroy();
- Log.e("Android_test", "Destroy");
- }
- }
转载于:https://blog.51cto.com/422787/724613