Android Oreo(8.0)系统TextView自动换行位置异常问题求助
问题原因及解决方案
这个问题我之前也碰到过!主要是Android 8.0(API 26)之后,旧版android.support.constraint.ConstraintLayout对match_parent的测量逻辑发生了变化导致的。
你当前的TextView设置了layout_width="match_parent",同时又通过ConstraintLayout的约束app:layout_constraintLeft_toLeftOf="parent"和app:layout_constraintRight_toRightOf="parent"加上左右margin来限制宽度。在Android 8.0之前,ConstraintLayout对这种场景的宽度计算比较宽松,但8.0之后,它对match_parent的处理更严格,导致TextView实际可用宽度被错误计算,从而出现非预期换行。
另外提个小建议:textSize应该用sp单位而不是dp,sp会适配系统的字体大小设置,对用户体验更友好~
修正后的代码
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lwz15.myapplication.MainActivity"> <TextView android:layout_width="0dp" <!-- 替换成match_constraint --> android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:textSize="16sp" <!-- 改用sp单位 --> android:text="请将设备插上电源后,等待一段时间后,直到设备启动完成" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
简单来说,0dp(即match_constraint)是ConstraintLayout中用来让控件根据约束条件自动计算宽度/高度的正确方式,而match_parent在ConstraintLayout里的行为在不同Android版本和支持库版本中存在兼容性问题,换成0dp就能解决这个换行问题啦。
内容的提问来源于stack exchange,提问作者lwz159
相关产品推荐
相关产品推荐

