2011年7月13日星期三

如何鎖定屏幕方向, setRequestedOrientation

我們可以調用 getResources().getConfiguration().orientation 獲得當前的屏幕方向, 然後調用 setRequestedOrientation() 方法鎖定屏幕方向.

例子:

鎖定屏幕方向

package com.AndroidFixOrientation;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

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

CheckBox fixOrientation = (CheckBox)findViewById(R.id.FixOrientation);

fixOrientation.setOnCheckedChangeListener(new OnCheckedChangeListener(){

int currentOrientation = getResources().getConfiguration().orientation;

public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
if(arg1){
switch(currentOrientation) {
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
default:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}else{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}});


}
}


沒有留言:

發佈留言