通过程序更改手机屏幕的显示方向需要使用setRequesetedOrientation()方法,获取当前显示方向是使用getRequestOrientation方法实现的,其中,在使用getRequestedOrientation()方法时需要传递SCREEN_ORIENTATION_LANDSCAPE(横屏) 和 SCREEN_ORIENTATION_PORTRAIT两个参数(竖屏)。程序一开始闲判断getRequestOrentation()的值是否为-1,表示在Activity属性里没有设置android:screenOrientation=“portrait”,这意味着即使点击按钮也无法判断屏幕的方向,不会进行更改方向的事件了。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this) ;
RadioGroup rg = new RadioGroup(this) ;
final RadioButton rb1 = new RadioButton(this) ;
final RadioButton rb2 = new RadioButton(this) ;
rg.addView(rb1) ;
rg.addView(rb2) ;
ll.addView(rg) ;
rb1.setText("横屏") ;
rb2.setText("竖屏") ;
setContentView(ll) ;
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == rb1.getId()){
if(getRequestedOrientation() == -1){
Toast.makeText(MainActivity.this, "无法区分横竖屏",Toast.LENGTH_LONG).show();
}else{ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) ;
}
}else if(checkedId == rb2.getId()){
if(getRequestedOrientation() == -1){
Toast.makeText(MainActivity.this, "无法区分横竖屏",Toast.LENGTH_LONG).show();
}else{ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) ;
}
}
Toast.makeText(MainActivity.this, ""+checkedId, Toast.LENGTH_LONG).show();
}
}) ;
}
<activity
android:screenOrientation="landscape"
android:name="com.example.a_wuyafeng.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>