我们知道Android在屏幕旋转之后,有两种情况发生:
第一种情况:销毁当前的Activity,也就是重新启动个Activity,然后走onCreate()、onStart()等流程。
第二种情况:不重新启动这个Activity而只做些动作。
第一种情况是Android中正常情况,第二种情况是你在manifest.xml里注册了android:config后的动作,你告诉系统当哪写配置改变后做什么。
言归正传,那我们如何动态检测当前屏幕方向及大小呢,请看下面的代码:
public class orientation extends Activity {
TextView textview = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview=(TextView)findViewById(R.id.textview);
int screenwidth=getWindowManager().getDefaultDisplay().getWidth();
int screenheight=getWindochanger codewManager().getDefaultDisplay().getHeight();
Log.d("orient", "now the screen width is :"+screenwidth+"screen height is:"+screenheight);
int orient=getRequestedOrientation();
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Log.d("orient", "now the screen orient is landscape");
}
else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
Log.d("orient", "now the screen orient is portrait");
}
}
}
看明白了吗,问题的根本是配置改变,那就找配置信息.getResources().getConfiguration即可获得当前配置对象,我们就可以使用getWindowManager().getDefaultDisplay().getHeight().getWidth()动态获取高度、宽度。