1)在AndroidManifest.xml中添加代码
android:configChanges="orientation|screenSize"
表示捕获旋转屏幕方向时触发onConfigurationChanged事件
文件全部代码如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidappdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidappdemo.MainActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize">
<!--申明activity要捕获的事件类型 -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2)修改MainActivity.java代码如下
package com.example.androidappdemo;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView1=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=(TextView)findViewById(R.id.textView1);
textView1.setText("加载屏幕");
}
/* *
* 屏幕旋转时调用此方法
* */
@Override
public void onConfigurationChanged(Configuration newConfig){
//newConfig.orientation获取当前屏幕状态时横向或者竖向
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
textView1.setText("现在是横屏");
}
if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
textView1.setText("现在是竖屏");
}
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}