啥都不说了,先上图!
代码很简单,如下:
public class screenOrientation extends Activity { private TextView mTextView01; private Button mButton01; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mButton01 = (Button) findViewById(R.id.myButton1); mTextView01 = (TextView) findViewById(R.id.myTextView1); /** * 需要注意的是要在AndroidManifest.xml\n添加android:screenOrientation属性 */ if (getRequestedOrientation() == -1) { mTextView01.setText(getResources().getText(0, "请添加android:screenOrientation属性 ")); } /* 当点击按钮旋转屏幕画面 */ mButton01.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { /* 方法一:重写getRequestedOrientation */ /* 若无法取得screenOrientation属性 */ if (getRequestedOrientation() == -1) { /* 提示无法进行画面旋转功能,因无法判别Orientation */ mTextView01.setText(getResources().getText(R.string.str_err_1001)); } else { if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { /* 若当下为横排,则更改为竖排呈现 */ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { /* 若当下为竖排,则更改为横排呈现 */ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } } }); } /** * 若要通过程序改变屏幕的方向,必须要覆盖setRequestedOrientation()方法, * 而若要取得当下的屏幕方向,必须要访问getRequestedOrientation()方法。 * 在AndroidManifest.xml中需要设置android * :screenOrientation属性,否则将无法通过getRequestedOrientation()来判断Activity的方向。 * * @param requestedOrientation */ @Override public void setRequestedOrientation(int requestedOrientation) { // TODO Auto-generated method stub /* 判断要更改的方向,以Toast提示 */ switch (requestedOrientation) { /* 更改为LANDSCAPE */ case (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE): mMakeTextToast(getResources().getText(R.string.str_msg1).toString(), false); break; /* 更改为PORTRAIT */ case (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT): mMakeTextToast(getResources().getText(R.string.str_msg2).toString(), false); break; } super.setRequestedOrientation(requestedOrientation); } @Override public int getRequestedOrientation() { // TODO Auto-generated method stub /* 此重写getRequestedOrientation方法,可取得当下屏幕的方向 */ return super.getRequestedOrientation(); } public void mMakeTextToast(String str, boolean isLong) { if (isLong == true) { Toast.makeText(screenOrientation.this, str, Toast.LENGTH_LONG).show(); } else { Toast.makeText(screenOrientation.this, str, Toast.LENGTH_SHORT).show(); } } }