2014-04-03 80 views
0

在我的应用程序中,我有MainActivty应该总是在protrait中查看。如果我将设备转向横向,则切换到TrendsActivity(以显示一些图)。当我切换回波泰特我只是在TrendsActivity称之为改变方向变化时的活动

@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); 
    } 
} 

然后:

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

这完成的全自动移回MainActivity活动这是由folliwing代码MainActivty完成。到现在为止还挺好。但是如果我在TrendsActivity中按下后退按钮,我会以横向模式返回到MainActivity,而我不想那样做。我试图调用MainActivity下面的代码:

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

这是不行的,因为现在的onConfigurationChanged()如果MainActivity不会被调用......

怎么办?

+1

为什么不直接在清单中指定说MainActivity应打开肖像模式和TrendsActivity应在开阔的景观中的代码?试过了吗? – JoelFernandes

回答

1

难道你不觉得你可能会通过简单地为横向模式指定一个备用xml并让MainActivity相应地行为来实现更简洁的设计吗?即使没有这一点,在定位变化上发起另一项活动也不会成为大多数用户期望的。

0

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); 
中的onResume()

使用这种MainActivty

+0

我试过了。它阻止了onConfigurationChanged()从beeing中调用jist,就像我在inRestart()中设置的那样( – buestad

0

你可以尝试设置在Android清单你的方向而已,试试下面的代码

android:screenOrientation="portrait" 

那么究竟你的代码在清单看起来像

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

)设置方向不会导致方向chnge –

+0

这会阻止onConfigurationChanged()从beeing调用,当我像setRequestedOrientation一样打开设备(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) ; – buestad

0

您应该添加这个到AndroidManifest

android:configChanges="orientation" 

这种方式告诉你的Android调用onConfigurationChanged当在姿势的改变。

+0

与上面相同的答案... – buestad

0

我解决了这个在我的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"