Why does DP not fit well?
Take blue Lake 360DP wide design draft, 60DP wide control as an example
Width (px) | density | 60 dp control (px) | The control of | |
---|---|---|---|---|
The design draft | 720 | 2 | 60*2=120px | 0.1666 |
Millet 9 | 1080 | 2.52 | 60 * 2.52 = 151.2 px | 0.14 |
Pixel XL | 1440 | 3.5 | 60 * 3.5 = 210 px | 0.1458 |
Glory Free Play 5 | 720 | 1.8375 | 60 * 1.8375 = 110.25 | 0.153125 |
Screen fit is to make the actual screen size ratio of the control the same as in the design draft
Toutiao adaptation scheme
Px = DP * density
Assume that the width of the design draft is 360DP. Based on this, in order to achieve the adaptation effect, the wide DP value of all devices should be 360DP. The device’s width PX value is physically fixed and the density can be modified to achieve this goal
fun customerDensity(app: Application) {
val displayMetrics = app.resources.displayMetrics
// Get the screen width
val screenWidth = displayMetrics.widthPixels // density = px / dp
val targetDensity = screenWidth / 360f
val targetDensityDpi = (160 * targetDensity).toInt()
displayMetrics.density = targetDensity
displayMetrics.densityDpi = targetDensityDpi
}
Copy the code
advantages
- Low cost, easy to implement
- Low intrusion and easy rollback
- Global adaptation
disadvantages
- Global adaptation, when the third-party library UI design rules are too different, the actual adaptation effect is very different
SmallestWidth qualifier fit
The principle of
The system will match dimens. XML in the values-SWdp folder according to the minimum screen width of the current device (smallestWidth). If not found, the system will look for the values-SWdp folder less than or equal to sw
Take the 360DP design draft as an example
Create dimens. XML under values-sw360dp as follows:
<resources>
<dimen name="dp_1">1dp</dimen>
<dimen name="dp_2">2dp</dimen>. <dimen name="dp_359">359dp</dimen>
<dimen name="dp_360">360dp</dimen>
</resources>
Copy the code
Based on the width of 360DP, the unit value of dimens. XML under values -SW380dp is 380/360=1.05555
<resources>
<dimen name="dp_1">1.05555 dp</dimen>
<dimen name="dp_2">2.11111 dp</dimen>. <dimen name="dp_359">378.944dp</dimen>
<dimen name="dp_360">380dp</dimen>
</resources>
Copy the code
advantages
- Stable, no performance loss
- Customize the adaptation range
disadvantages
- It is highly intrusive and difficult to maintain
- Model coverage is limited, the wider the adaptation range, the larger the corresponding inclusion size
ConstraintLayout Percentage width and height
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintWidth_percent="0.5"
app:layout_constraintHeight_percent="0.1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
Copy the code