最近已经开发好几年的项目需要适配平板,同时平板上面需要横竖屏进行切换,还要在手机上能够正常使用,经过调研以后,在改动最小的情况下,对项目进行必要的修改,完成相应的需求,现在将大概的思路和涉及到的内容整理如下:
清单文件放开强制横竖屏的限制
横竖屏切换时页面需要重绘,生命周期会重新走,为了防止多次重复走生命周期,在清单文件中进行设置
android:configChanges="keyboardHidden|orientation|screenSize"
对界面进行分屏处理
左右分屏,base中进行横向和竖向判断,进行全屏或者占屏幕几份的处理(初次加载)
@Override
protected void onStart() {
super.onStart();
setScreenDirection();
}
private void setScreenDirection() {
boolean screenDirection = ScreenDirectionUtil.getInstance().getScreenDirection(this);
if (screenDirection) {
ScreenDirectionUtil.getInstance().setScreenProportion(this,1,1,2);
}else {
ScreenDirectionUtil.getInstance().setScreenProportion(this,5,3,2);
}
}
由于设置了configChanges,横竖屏切换时生命周期不再走,在onConfigurationChanged中判断横竖屏方向,进行屏幕占比动态配置
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) {
// 横屏
ScreenDirectionUtil.getInstance().setScreenProportion(this,5,3,2);
}else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT) {
// 竖屏
ScreenDirectionUtil.getInstance().setScreenProportion(this,1,1,2);
}
}
设置activity的穿透点击,平板的左侧一级页面可以一直点击
清单文件中给activity设置style
android:theme="@style/transparent_activity"
<style name="transparent_activity" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>
</style>
activity中设置可穿透点击
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
屏幕的占比动态设置方法
public void setScreenProportion(Activity context, int proportion,int number,int position) {
// 为获取屏幕宽、高
Display display = context.getWindowManager().getDefaultDisplay();
Window win = context.getWindow();
win.getDecorView().setPadding(0, 0, 0, 0);
WindowManager.LayoutParams lp = win.getAttributes();
if (proportion > 1){
lp.width = (int) (display.getWidth() * number / proportion);
}else {
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
}
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
//设置对话框置顶显示
lp.gravity = Gravity.TOP;
//设置对话框置顶显示
if (position == 1) {
lp.gravity = Gravity.LEFT;
}else {
lp.gravity = Gravity.RIGHT;
}
win.setAttributes(lp);
}
是否是平板的判断方法
public boolean isPad(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
判断是横屏还是竖屏
public boolean getScreenDirection(Context context) {
DisplayMetrics d = context.getResources().getDisplayMetrics();
if (d.heightPixels > d.widthPixels) {
return true;
}
return false;
}
上面的是主要涉及到的相关注意事项和用到的方法
以上就是android现有项目轻微改动适配平板心得的详细内容,更多关于android现有项目适配平板的资料请关注编程网其它相关文章!