2012-02-14 39 views
1

我的Android应用程序中有一个Activity,它根据方向设置不同的布局XML作为其视图。我已在清单中声明android:configChanges="orientation"。现在被称为 - 但这个时候新的方向已经生效。指定android:configChanges =“orientation”时保存状态_before_ orientation change

我的目标是尝试挂钩生命周期并尝试保存之前的新定位生效;以便在我回到当前的方向时恢复状态。

我对它进行了如下操作,但我不确定这是否是正确的方式。我的程序涉及将状态保存在中,然后调用setContentView()来设置新方向的布局。

public class SwitchOrientationActivity extends Activity { 

    private View mLandscape, mPortrait; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     LayoutInflater li = LayoutInflater.from(this); 
     mLandscape = li.inflate(R.layout.landscape, null); 
     mPortrait = li.inflate(R.layout.portrait, null); 
    } 

    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 

     if (Configuration.ORIENTATION_LANDSCAPE == newConfig.orientation) { 
      switchToLandscape(); 
     } else { 
      switchToPortrait(); 
     } 
    } 

    private void switchToPortrait() { 

     /* 
     * Use mLandscape.findViewById() to get to the views and save the values 
     * I'm interested in. 
     */ 
     saveLanscapeState(); 
     setContentView(mPortrait); 
    } 

    private void switchToLandscape() { 
     /* 
     * Use mPortrait.findViewById() to get to the views and save the values 
     * I'm interested in. 
     */ 
     savePortraitState(); 
     setContentView(mLandscape); 

    } 
} 

有没有更好的方法来实现这个目标?

+0

由于方向更改导致活动被破坏并重新创建,您是否总能保存onPause,onStop或onDestroy方法? – 2012-02-14 04:12:27

+0

@Nick Campion:如果你在Manifest文件中声明了android:configChanges =“orientation”,那么当方向改变时活动不再被销毁/创建 – 2012-02-14 04:17:05

+0

啊,我学到了一些东西。 – 2012-02-14 04:22:16

回答

0

android:configChanges="orientation"导致您的活动不会在方向更改中重新启动,因此跳过正常的生命周期。我建议,你把它拿出来,然后执行onRetainNonConfigurationInstance()并在onCreate或onRestoreInstanceState中恢复你的状态。请参阅article以获取更多信息

+0

实际上,我不需要在定位更改时重新启动或重新创建我的活动。我希望它在2种不同的布局之间切换 - 每种布局都提供单独的功能(肖像显示使用图形的一些值;横向显示值的历史图表)。另外,即使我使用'onRetainNonConfigurationInstance()',我仍然需要在那里保存视图,所以它会引入内存泄漏的风险。 – curioustechizen 2012-02-14 05:34:42

相关问题