5中适配
1图片适配(不同像素密度的手机加载不同资源文件夹的图片)
已知屏幕的宽和高通过勾股定理计算出屏幕的密度(dpi)
例子:
已知1280*720的手机(5寸)
1280(屏幕的高度上有1280个像素点)
720(屏幕的宽度上有720个像素点)
勾股定理
1468.6(斜边的像素点) = Math.sqrt(1280*1280+720*720)(开方)
每英寸上的像素点就屏幕密度
1468.6/5(屏幕英寸) = 293.72 dpi(密度)
根据这个密度值对照下图,系统就加载xhdpi下面的图片
文件夹
屏幕比例
dp转px
ldpi
320*240
1dp= 0.75px
mdpi
480*320
1dp=1px
hdpi
800*480
1dp=1.5px
xhdpi
1280*720
1dp=2px
xxhdpi
1920*1080
1dp=3px
怎么保证在不同手机上图片不变形?
利用自定义控件,在图片的控件外层包裹自定义控件全路径名,该自定义控件继承LinearLayout
<com.itheima.googleplay32.views.RatioFrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:picRatio="2.43" app:relative="width"> <ImageView android:id="@+id/item_subject_iv_icon" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitXY"/> </com.itheima.googleplay32.views.RatioFrameLayout>
在onMeasure方法中
已知图片的宽度动态计算高度
/** * 已知宽度动态计算高度 */ //图片的比例值(根据图片的宽和高计算的) float imageScale = 2.42f; //获取模式 int mode = MeasureSpec.getMode(widthMeasureSpec); //模式等于确切的模式 if(mode == MeasureSpec.EXACTLY){ //获取容器的宽度,使用该方法的前提是,必须知道模式 int preatWidth = MeasureSpec.getSize(widthMeasureSpec); int preatHeight = (int) (preatWidth/imageScale+.5f); Log.d(TAG, "onMeasure: --------"+UIUtils.px2Dip(preatHeight)); //保存测量结果 setMeasuredDimension(preatWidth,preatHeight); //孩子的宽度 int childwidth = preatWidth - getPaddingLeft() - getPaddingRight(); int childHeight = preatHeight - getPaddingBottom() - getPaddingTop(); //根据孩子的宽和高或的带有模式的宽和高 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childwidth, MeasureSpec.EXACTLY); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight,MeasureSpec.EXACTLY); //测绘孩子 measureChildren(childWidthMeasureSpec, childHeightMeasureSpec); }else{ super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
2demin.xml适配
根据不同的手机新建values-1280x720文件加,在该文件夹下创建dimens.xml
系统会根据当前手机的密度,取对应的文件夹下找对应的值
默认会找values文件夹下的值,也要在默认的时候创建默认下的width值
在xml文件夹中引用
3布局适配(
不同像素密度的手机加载不同layout的布局文件
)
布局适配和dimen适配的原理一样,新建一个指定手机的布局Layout-1280x720,
系统会根据当前手机的密度,取对应的文件夹下找对应的值
4java代码适配(控件的宽高,根据屏幕的宽高比例值去设置的)
以textView显示屏幕的1/2为例
在任何手机上的运行效果都是一样的
5权重适配(这个基本都知道就是weight)