在方向更改上做些什么

问题描述:

我想在用户旋转屏幕时更改某些内容,例如变量值。在方向更改上做些什么

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

this

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

我想抓住当前的方向,开始做我想做的事情。

+0

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

在某些设备上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

使用活动的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%,请引用您的来源 –

您必须覆盖在你的活动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"); 
}