You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用ConstraintLayout实现视图半嵌半露及TextView半置另一视图底部?

嘿,我来帮你解决这两个ConstraintLayout的布局问题!之前用Baseline没达到预期太正常了——Baseline是用来对齐文字基线的,根本不是干这个活的工具~咱们换个思路,用ConstraintLayout的核心约束逻辑就能轻松实现需求。

需求1:让一个视图一半嵌入另一视图内部、一半暴露在外

这个需求的核心是让子视图的中心对齐父视图的边缘,这样子视图自然会一半在里一半在外。用ConstraintLayout的双向约束就能实现,不需要复杂的计算:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 作为容器的目标视图 -->
    <View
        android:id="@+id/container_view"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#FFCCCC"
        app:layout_constraintCenterInParent="true"/>

    <!-- 一半嵌入、一半在外的子视图 -->
    <View
        android:id="@+id/embedded_view"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#CCFFCC"
        <!-- 同时把顶部和底部约束到容器的底部边缘 -->
        app:layout_constraintTop_toBottomOf="@id/container_view"
        app:layout_constraintBottom_toBottomOf="@id/container_view"/>

</androidx.constraintlayout.widget.ConstraintLayout>

原理很简单:当你把一个视图的两个对立边缘(比如top和bottom)都约束到同一个目标边缘时,ConstraintLayout会自动将这个视图的中心对齐到目标边缘,刚好实现一半嵌入、一半外露的效果。如果是横向需求(比如从左侧/右侧半嵌),只需要把约束换成leftright即可。

需求2:TextView一半位于另一视图内部、一半位于外部(底部对齐)

同样用上面的核心逻辑,只不过这次对象是TextView——别再用Baseline啦,直接约束TextView的视图边缘就行:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 目标视图 -->
    <View
        android:id="@+id/target_view"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#FFCCCC"
        app:layout_constraintCenterInParent="true"/>

    <!-- 半嵌的TextView -->
    <TextView
        android:id="@+id/half_embedded_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是半嵌的文本"
        android:textSize="18sp"
        android:background="#CCFFFF"
        <!-- 把TextView的顶部和底部都约束到目标视图的底部 -->
        app:layout_constraintTop_toBottomOf="@id/target_view"
        app:layout_constraintBottom_toBottomOf="@id/target_view"/>

</androidx.constraintlayout.widget.ConstraintLayout>

哪怕TextView是wrap_content高度,这个方法也完全适用——ConstraintLayout会自动计算TextView的中心,对齐到目标视图的底部边缘,完美实现一半在内部、一半在外部的效果。

如果需要更灵活的适配(比如目标视图尺寸动态变化),这个方案也能自动适配,不需要手动调整任何数值,非常省心。

内容的提问来源于stack exchange,提问作者Antonio Henrique

火山引擎 最新活动