Android MotionLayout中设置多行文本时TextView显示异常问题
MotionLayout下TextView多行文本首次点击不显示问题解决方案
问题原因
MotionLayout会缓存ConstraintSet的视图状态,你的初始配置中TextView不可见且无文本,其高度被计算为0。当设置多行文本后,TextView高度发生变化,但MotionLayout未及时更新缓存的布局信息,导致首次显示时仍使用旧的高度值,因此看不到内容;单行文本因高度变化极小,刚好适配缓存尺寸,所以能正常显示。
解决方法
方法1:完善MotionScene的ConstraintSet配置
在activity_main_scene.xml的start和end ConstraintSet中明确TextView的约束规则,让MotionLayout正确跟踪视图状态:
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android" xmlns:motion="http://schemas.android.com/apk/res-auto"> <Transition motion:constraintSetEnd="@+id/end" motion:constraintSetStart="@id/start" motion:duration="1000"> </Transition> <ConstraintSet android:id="@+id/start"> <Constraint android:id="@+id/textView"> android:layout_width="0dp" android:layout_height="wrap_content" android:visibility="invisible" motion:layout_constraintBottom_toBottomOf="parent" motion:layout_constraintEnd_toEndOf="parent" motion:layout_constraintStart_toStartOf="parent" </Constraint> </ConstraintSet> <ConstraintSet android:id="@+id/end"> <Constraint android:id="@+id/textView"> android:layout_width="0dp" android:layout_height="wrap_content" android:visibility="visible" motion:layout_constraintBottom_toBottomOf="parent" motion:layout_constraintEnd_toEndOf="parent" motion:layout_constraintStart_toStartOf="parent" </Constraint> </ConstraintSet> </MotionScene>
然后在代码中通过切换ConstraintSet来控制显示:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button = findViewById<Button>(R.id.button) val textView = findViewById<TextView>(R.id.textView) val motionLayout = findViewById<MotionLayout>(R.id.motionLayout) // 给根布局添加id: motionLayout button.setOnClickListener { textView.setText("Some dummy text jtext text text text texte text texte txjkk ggg gggg ggggg gg trdff rrrrrr rrrr") motionLayout.transitionToEnd() } } }
方法2:强制MotionLayout重计算布局
如果不想修改MotionScene,可在设置文本和可见性后,触发MotionLayout重新布局:
button.setOnClickListener { textView.setText("Some dummy text jtext text text text texte text texte txjkk ggg gggg ggggg gg trdff rrrrrr rrrr") textView.visibility = View.VISIBLE textView.post { findViewById<MotionLayout>(R.id.motionLayout).requestLayout() } }
使用post确保文本已完全设置,再触发布局更新。
方法3:设置TextView最小高度
给TextView添加最小高度,避免初始无文本时高度被计算为0:
<TextView android:id="@+id/textView" android:layout_width="0dp" android:layout_height="wrap_content" android:minHeight="40dp" android:visibility="invisible" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" />
内容的提问来源于stack exchange,提问作者Abdo21
相关产品推荐
相关产品推荐

