使用CoordinatorLayout时ViewMoreTextView库展开文本异常问题
解决ViewMoreTextView返回再进页面“Read more”消失的问题
问题背景
使用it.mike5v:viewmore-textview:1.1.3库时,首次进入页面ViewMoreTextView正常显示“Read more”文本,但从页面返回再进入后,该文本消失。布局中该View嵌套在CoordinatorLayout+AppBarLayout+NestedScrollView结构里,且该库是最符合需求的选择。
可能原因
这个库的内部状态管理在视图重建(比如Fragment复用、页面返回后重新创建)时存在缺陷,没有正确重置折叠/展开状态;或者CoordinatorLayout的布局刷新、NestedScrollView的滚动状态影响了ViewMoreTextView的内容测量,导致它错误判断文本不需要折叠,从而隐藏了“Read more”。
解决方案
1. 手动重置View状态
在Fragment的onResume中强制触发ViewMoreTextView重新计算状态,确保每次进入页面都重新判断是否需要显示“Read more”:
Kotlin代码:
override fun onResume() { super.onResume() binding.masterclassDescription.post { // 重置到初始折叠状态 binding.masterclassDescription.reset() // 如果reset无效,直接调用collapse强制折叠 // binding.masterclassDescription.collapse() } }
Java代码:
@Override public void onResume() { super.onResume(); binding.masterclassDescription.post(() -> { binding.masterclassDescription.reset(); // 备选:binding.masterclassDescription.collapse(); }); }
2. 禁用视图状态保存
阻止系统保存ViewMoreTextView的状态,避免复用旧状态导致显示异常,在布局中添加属性:
<it.mike5v.viewmoretextview.ViewMoreTextView android:id="@+id/masterclass_description" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/text_light_color" android:layout_marginTop="8dp" android:saveEnabled="false" <!-- 添加此行 --> app:ellipsizeText="@string/read_more" app:ellipsizeTextColor="@color/white" app:duration="100" app:visibleLines="10" />
3. 确保文本加载后再初始化
如果文本是异步加载(比如从接口获取),要在设置文本后手动触发状态计算:
// 假设文本加载完成后设置 binding.masterclassDescription.text = fetchedDescription binding.masterclassDescription.post { binding.masterclassDescription.reset() }
原理说明
CoordinatorLayout的布局机制会延迟子View的测量时机,而Fragment的视图复用会保留View的旧状态。通过手动重置状态或禁用状态保存,能让ViewMoreTextView每次进入页面时都重新计算文本高度,判断是否需要显示“Read more”。
内容的提问来源于stack exchange,提问作者flutra
相关产品推荐
相关产品推荐

