2011-12-16 85 views
1

我認爲我有類似於許多舊問題的問題,但它不一樣。如何防止設備旋轉時的佈局變化?

我希望應用程序不要在應用程序運行時旋轉設備時更改佈局方向。 這個:

android:screenOrientation = "portrait" 

......沒有辦法。我不想以固定的方向申請。我想只是爲了防止它在應用程序工作時發生改變。

此:

android:configChanges="orientation" 

...不會做的伎倆。設置後,應用程序不會重新啓動,佈局不會更改爲其他佈局,但當前佈局會根據新的設備方向進行旋轉和拉伸。

我想實現的所有目標是在活動開始時根據方向選擇適當的佈局,然後在應用程序完成之前保持相同的佈局和相同的佈局方向。

任何人都知道如何輕鬆做到這一點?

回答

1

使用此代碼將應用程序限制在相同的方向,直到應用程序完成,調用createInstance後使用此代碼,然後在相應的資源文件夾中使用適當的佈局,用於肖像res /佈局以及橫向使用res/layout-land。 ..

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); 

    int orientation = display.getOrientation(); 

    if(orientation == Configuration.ORIENTATION_PORTRAIT){ 

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
    } 

    if(orientation == Configuration.ORIENTATION_LANDSCAPE){ 
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
    } 
+0

太好了。非常感謝你! – ardabro 2011-12-16 13:38:21

0

Android系統通過銷燬和重新創建Activity來自動處理旋轉。 Andrdoid稱之爲「配置更改」,有幾種可能發生的情況(請參閱http://developer.android.com/reference/android/R.attr.html#configChanges)。

這是不是你想要的,這樣你就可以表明一種配置的變化要在AndroidManifest.xml手動處理:

<Activity ... android:configChanges="orientation" /> 

可能,那麼你要重寫Activity.onConfigurationChanged(Configuration)作爲要處理的配置變化。

0

解決的辦法是找出的onCreate屏幕方向(),然後設置方向:

/* First, get the Display from the WindowManager */ 
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); 

/* Now we can retrieve all display-related infos */ 
int width = display.getWidth(); 
int height = display.getHeight(); 
int orientation = display.getOrientation(); 

,然後設置相應的方向:setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_XXXXX)

0

試試吧:

package com.exercise.AndroidOrientation; 

import android.app.Activity; 
import android.content.pm.ActivityInfo; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 

public class AndroidOrientationActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    Button buttonSetPortrait = (Button)findViewById(R.id.setPortrait); 
    Button buttonSetLandscape = (Button)findViewById(R.id.setLandscape); 

    buttonSetPortrait.setOnClickListener(new Button.OnClickListener(){ 

@Override 
public void onClick(View arg0) { 
     // TODO Auto-generated method stub 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
}}); 

    buttonSetLandscape.setOnClickListener(new Button.OnClickListener(){ 

@Override 
public void onClick(View arg0) { 
     // TODO Auto-generated method stub 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
    }}); 
} 
}