Chinaunix首页 | 论坛 | 博客
  • 博客访问: 799810
  • 博文数量: 76
  • 博客积分: 2211
  • 博客等级: 上尉
  • 技术积分: 1693
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-26 19:36
文章分类

全部博文(76)

文章存档

2012年(67)

2011年(9)

分类: 嵌入式

2012-05-07 18:56:07

当屏幕切换的时候,系统会重新呼叫当前Activity的OnCreate方法,我们可以用以下方法放在你的OnCreate中来检查当前的方向,然后可以让你的SetContentView来载入不同的Layout xml.

if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {

Log.i("info", "landscape");

}

else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {

Log.i("info", "portrait");

}

在屏幕切换的时候
首先需要在androidmanifest.xml中加入配置
android:configChanges="orientation|keyboardHidden|navigation
这样在程序中. Activity就不会重复的调用onCreate(),甚至不会调用onPause.onResume.只会调用一个onConfigurationChanged(Configuration newConfig)
这是在XML加入配置选项的前提下.

如果在就加入选项的前提下.如上所说. Activity会重新激活onCreate方法

根据你自己的需求来选择配置改变时的处理机制这样比较好一点。

package com.fuming.chen.configuration;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;

public class AdnroidStudyDemos extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(this.getResources() .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
Log.e(".......Trace......", "********load portrait layout");
setContentView(R.layout.main);
}
else if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Log.e(".......Trace......", "************* load landscape ");
setContentView(R.layout.main_landscape);
}
}
public void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
if(this.getResources() .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
Log.e(".......Trace......", "********this is a portrait");
}
else if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Log.e(".......Trace......", "this is a landscape *************");
}
}
}

super.onConfigurationChanged(configuration); 是必须的,否则会报异常。。。

阅读(2626) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~