里面所展示的MainActivity.class和activity_main.xml是无用的:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/but_landscape" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切换成横屏" /> <Button android:id="@+id/but_portrait" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切换成竖屏" /> </LinearLayout>
HomeActivity.class:
package com.example.vedio_project_heng_shu; import android.app.Activity; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class HomeActivity extends Activity implements OnClickListener { private Button mBtnLandscape; private Button mBtnPortrait; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); mBtnLandscape = (Button) findViewById(R.id.but_landscape); mBtnPortrait = (Button) findViewById(R.id.but_portrait); mBtnLandscape.setOnClickListener(this); mBtnPortrait.setOnClickListener(this); } public void onClick(View v) { // TODO Auto-generated method stub if(v == mBtnLandscape){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }else{ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); String message=newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE ? "屏幕设置为:横屏" : "屏幕设置为:竖屏"; Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } }
效果图: