簡體   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