2016-08-14 61 views
0

我想在用戶旋轉屏幕時更改某些內容,例如變量值。在方向更改上做些什麼

我知道我可以使用類似的有方向:

this

,但我不想定義if portrait do this, if landscape do this

我想抓住當前的方向,開始做我想做的事情。

+0

你的意思是你不'不想從 '公共無效onConfigurationChanged(配置newConfig)' –

回答

0

在某些設備上void onConfigurationChanged()可能會崩潰。用戶將使用此代碼獲取當前的屏幕方向。

public int getScreenOrientation() 
{ 
    Display getOrient = getActivity().getWindowManager().getDefaultDisplay(); 
    int orientation = Configuration.ORIENTATION_UNDEFINED; 
    if(getOrient.getWidth()==getOrient.getHeight()){ 
     orientation = Configuration.ORIENTATION_SQUARE; 
    } else{ 
     if(getOrient.getWidth() < getOrient.getHeight()){ 
      orientation = Configuration.ORIENTATION_PORTRAIT; 
     }else { 
      orientation = Configuration.ORIENTATION_LANDSCAPE; 
     } 
    } 
    return orientation; 
} 

並使用

if (orientation==1)  // 1 for Configuration.ORIENTATION_PORTRAIT 
{       // 2 for Configuration.ORIENTATION_LANDSCAPE 
    //your code    // 0 for Configuration.ORIENTATION_SQUARE 
} 
+0

'但我想檢測方向的變化。不使用'1'的肖像,'2'的景觀等 – George

+0

「onConfigurationChanged ()可能會崩潰「源? – njzk2

0

使用活動的onConfigurationChanged方法。請看下面的代碼:

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

    // Checks the orientation of the screen 
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 
     Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); 
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ 
     Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); 
    } 
} 

你也有你的清單文件編輯相應的元素包括了android:configChanges請看下面的代碼:

<activity android:name=".MyActivity" 
      android:configChanges="orientation|keyboardHidden" 
      android:label="@string/app_name"> 

注:從Android 3.2(API級別13)或更高,則當設備在縱向和橫向之間切換時,「屏幕尺寸」也會改變。因此,如果要在開發API級別13或更高版本時防止由於方向更改而導致運行時重新啓動,則必須爲API級別13或更高版本設置android:configChanges =「orientation | screenSize」。

希望這將幫助你.. :)

+0

謝謝,但正如我告訴過你的,我不想讓屏幕取向。我想在取向改變時做些事情。 :) – George

+0

什麼時候方向會改變所有的時間調用onConfigurationChanged()方法,請把你的代碼放在onConfigurationChanged()方法中,這是父類的覆蓋方法,所以請不要擔心它的方向自動調用方向時正確 –

+0

這實質上是複製並從[Android文檔](https://developer.android.com/guide/topics/resources/runtime-changes.html)粘貼,如果答案不是100%,請引用您的來源 –

0

您必須覆蓋在你的活動onConfigurationChanged方法,並檢查當前方向和做任何你想做這樣

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

    // Check orientation 
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 
      DoSomethingForLandscapeOrientation();(); 
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ 
      DoSomethingForPortraitOrientation(); 
    } 
} 


private void DoSomethingForLandscapeOrientation(){ 
    Log.i("Method For","Landscape"); 
} 

private void DoSomethingForPortraitOrientation(){ 
    Log.i("Method For","Portrait"); 
}