Android入门笔记之更改手机屏幕方向
<1>简介
通过一个按钮组来改变横屏竖屏显示。
<2>关键步骤
主要通过android.app.activity.getRequestedOrientation()来感知屏幕的状态,若返回-1则无法识别屏幕状态。用setRequestedOrientation来设置屏幕状态。
<3>出现的问题
注意资源文件不能用大写字母命名,否则R文件无法识别。
<4>代码及解释
Activity_changescreen.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android:id="@+id/RadioGroup01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:text="竖屏"
android:id="@+id/screenbut1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioButton>
<RadioButton
android:text="横屏"
android:id="@+id/screenbut2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioButton>
</RadioGroup>
</LinearLayout>
ChangeScreenActivity:
package com.func;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.test.R;
public class ChangeScreenActivity extends Activity{
/**
* @ProjectName: [androidtest]
* @Package: [com.func.ChangeScreenActivity.java]
* @ClassName: [ChangeScreenActivity]
* @Description:
* @Author: [gmj]
* @CreateDate: [2013-9-7 下午1:41:59]
* @Version: [v1.0]
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_changescreen);
RadioGroup rg=(RadioGroup)this.findViewById(R.id.RadioGroup01);
final RadioButton rbH=(RadioButton)this.findViewById(R.id.screenbut1);//横屏按钮
final RadioButton rbV=(RadioButton)this.findViewById(R.id.screenbut2);//竖屏按钮
if(getRequestedOrientation()==-1)
{
Toast.makeText(
ChangeScreenActivity.this,
"无法区分横竖屏!!",
Toast.LENGTH_SHORT).show();
}
RadioGroup.OnCheckedChangeListener mChange=new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if(checkedId==rbH.getId())//横屏按钮
{
if(getRequestedOrientation()==-1)
{
Toast.makeText(
ChangeScreenActivity.this,
"无法区分横竖屏!!",
Toast.LENGTH_SHORT).show();
}else
if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)//若为横屏
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置为竖屏
Toast.makeText(
ChangeScreenActivity.this,
"现在是竖屏!!",
Toast.LENGTH_SHORT).show();
}
}else if(checkedId==rbV.getId())//竖屏按钮
{
if(getRequestedOrientation()==-1)
{
Toast.makeText(
ChangeScreenActivity.this,
"无法区分横竖屏!!",
Toast.LENGTH_SHORT).show();
}else
if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//若为竖屏
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//设置为横屏
Toast.makeText(
ChangeScreenActivity.this,
"现在是横屏!!",
Toast.LENGTH_SHORT).show();
}
}
}
};
rg.setOnCheckedChangeListener(mChange);//RadioGroup添加监听器
}
}