当前位置: 移动技术网 > 移动技术>移动开发>Android > android横竖屏切换不重启activity解决方案

android横竖屏切换不重启activity解决方案

2019年07月24日  | 移动技术网移动技术  | 我要评论
部分网友会发现activity在切换到后台或布局从横屏landscape切换到portrait,会重新切换activity会触发一次oncreate方法,我们可以在androidmanifest.xml中的activit元素加入这个属性android:configchanges="orientation|keyboardhidden" 即可,比如
<activity android:name=".android123" android:configchanges="orientation|keyboardhidden" android:label="@string/app_name">
java代码
复制代码 代码如下:

/* 声明display对象,以取得屏幕宽高 */
final display defaultdisplay = getwindow().getwindowmanager()
.getdefaultdisplay();

intscreenh = defaultdisplay.getheight();
intscreenw = defaultdisplay.getwidth();

/* 如果为landscape */
if (intscreenw > intscreenh)
{
/* landscape => portrait */
setrequestedorientation(activityinfo.screen_orientation_portrait);
} else
{
/* portrait => landscape */
setrequestedorientation(activityinfo.screen_orientation_landscape);
}
/* 声明display对象,以取得屏幕宽高 */
final display defaultdisplay = getwindow().getwindowmanager()
.getdefaultdisplay();
intscreenh = defaultdisplay.getheight();
intscreenw = defaultdisplay.getwidth();
/* 如果为landscape */
if (intscreenw > intscreenh)
{
/* landscape => portrait */
setrequestedorientation(activityinfo.screen_orientation_portrait);
} else
{
/* portrait => landscape */
setrequestedorientation(activityinfo.screen_orientation_landscape);
}

同时在activity的java文件中重载onconfigurationchanged(configuration newconfig)这个方法,这样就不会在布局切换或窗口切换时重载oncreate等方法。代码如下:
java代码
复制代码 代码如下:

@override
public void onconfigurationchanged(configuration newconfig)
{
super.onconfigurationchanged(newconfig);
if (this.getresources().getconfiguration().orientation == configuration.orientation_landscape)
{
//land
}
else if (this.getresources().getconfiguration().orientation == configuration.orientation_portrait)
{
//port
}
}
@override
public void onconfigurationchanged(configuration newconfig)
{
super.onconfigurationchanged(newconfig);
if (this.getresources().getconfiguration().orientation == configuration.orientation_landscape)
{
//land
}
else if (this.getresources().getconfiguration().orientation == configuration.orientation_portrait)
{
//port
}
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网