Android中如何获取ConstraintLayout Flow布局的行数?
解决ConstraintLayout Flow换行时隐藏分隔符的问题
Flow Helper确实没有内置的行数判断API,不过可以通过监听布局变化或自定义Flow的方式实现需求,以下是两种可行方案:
方案1:监听布局变化,通过子视图位置判断换行
利用同一行子视图的顶部坐标一致的特性,在Flow布局完成后对比TextView1和TextView2的top值,判断是否换行:
flow.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> val isWrapped = textView2.top > textView1.top delimiterView.visibility = if (isWrapped) View.GONE else View.VISIBLE }
- 前提:确保Flow的
wrapMode设置为chain或aligned,保证布局逻辑符合预期。 - 补充:如果TextView2的文本是动态变化的,需要给它添加
TextWatcher,在文本改变时调用flow.requestLayout()触发重新布局检查:textView2.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { flow.requestLayout() } override fun afterTextChanged(s: Editable?) {} })
方案2:自定义Flow子类,追踪布局行数
通过重写Flow的onMeasure方法,统计子视图的实际行数:
class TrackableFlow @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : Flow(context, attrs, defStyleAttr) { private var currentLineCount = 0 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) currentLineCount = 0 var lastChildTop = -1 for (i in 0 until childCount) { val child = getChildAt(i) if (child.visibility != View.GONE) { val childTop = child.top if (childTop != lastChildTop) { currentLineCount++ lastChildTop = childTop } } } } fun getLineCount(): Int = currentLineCount }
之后在布局监听中通过行数判断:
trackableFlow.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> delimiterView.visibility = if (trackableFlow.getLineCount() > 1) View.GONE else View.VISIBLE }
内容的提问来源于stack exchange,提问作者AT Amrani
相关产品推荐
相关产品推荐

