繁体   English   中英

方向改变时改变活动

[英]Change activity when orientation changes

在我的应用程序中,我具有MainActivty,应始终按主视图进行查看。 如果将设备转到横向,则切换到TrendsActivity(以显示一些图形)。 这是通过MainActivty中的愚弄代码完成的:

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    {
        Intent intent = new Intent(this, TrendsActivity.class);
        startActivity(intent);
    } 
}

然后,当我切换回肖像时,我只需在TrendsActivity中调用它即可:

    @Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
    {
        finish();
    }
}

这样就完成了活动,并自动移回MainActivity。 到现在为止还挺好。 但是,如果我在TrendsActivity中按下返回按钮,则会以横向模式返回MainActivity,但我不希望那样。 我试图在MainActivity中调用以下代码:

    @Override
protected void onRestart()
{
    super.onRestart();
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}

这是行不通的,因为现在如果从不调用MainActivity的onConfigurationChanged()……

该怎么办?

您是否不认为通过简单地为横向模式指定备用xml并让MainActivity相应地工作,可能会实现更简洁的设计? 即使没有这些,大多数用户也不会期望启动另一个有关方向改变的活动。

用这个

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

在MainActivty的onResume()中

您可以尝试仅在android清单中设置方向,请尝试以下代码

android:screenOrientation="portrait"

所以清单中的代码看起来确实像

<activity
   android:name=".yourActivityName"
   android:screenOrientation="portrait"
</activity>

您应该将此添加到AndroidManifest

android:configChanges="orientation"

这样,您可以告诉Android在方向更改时调用onConfigurationChanged

我通过更改MainActivity中的代码来解决此问题,只需更改布局XML,如fremmedehenvendelser建议(Tusen takk!)。

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    {
        //setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
        setContentView(R.layout.activity_trends);
    }
    else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
    {
        setContentView(R.layout.activity_main);
    } 
}

下一个问题是设置主题以使此布局以全屏显示。 被注释掉的代码不起作用...在清单上添加TrendsActivity之前

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM