如何在Constraint Layout中横向匹配两个非矩形背景视图
解决ConstraintLayout中非矩形视图横向组合问题
嘿,刚好做过类似的需求,这就给你一步步拆解怎么实现:
第一步:保存形状资源
先把你提供的两个Vector Drawable分别存到res/drawable目录下:
左侧背景(left_background.xml)
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="234dp" android:height="84dp" android:viewportWidth="234" android:viewportHeight="84"> <path android:pathData="M24,0L234,0L210,84L24,84C10.745,84 0,73.255 0,60L0,24C-0,10.745 10.745,0 24,0Z" android:strokeWidth="1" android:fillColor="#FFCD0D" android:fillType="evenOdd" android:strokeColor="#00000000"/> </vector>
右侧背景(right_background.xml)
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="134dp" android:height="84dp" android:viewportWidth="134" android:viewportHeight="84"> <path android:pathData="M24,2.06981099e-11 L110,0 C123.254834,-2.48646561e-12 134,10.745166 134,24 L134,60 C134,73.254834 123.254834,84 110,84 L0,84 L24,2.06981099e-11 Z" android:strokeWidth="1" android:fillColor="#FFD949" android:fillType="evenOdd" android:strokeColor="#00000000"/> </vector>
第二步:ConstraintLayout布局实现
核心是让两个视图无缝贴合,高度完全匹配,横向排列。这里要注意去掉Button默认的padding,避免出现缝隙:
<?xml version="1.0" encoding="utf-8"?> <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="wrap_content" android:padding="16dp"> <!-- 左侧TextView --> <TextView android:id="@+id/left_text_view" android:layout_width="wrap_content" android:layout_height="84dp" android:background="@drawable/left_background" android:gravity="center" android:text="左侧文本内容" android:textColor="#000" android:textSize="18sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> <!-- 右侧Button --> <Button android:id="@+id/right_button" android:layout_width="wrap_content" android:layout_height="84dp" android:background="@drawable/right_background" android:padding="0dp" android:gravity="center" android:text="右侧按钮" android:textColor="#000" android:textSize="18sp" app:layout_constraintStart_toEndOf="@+id/left_text_view" app:layout_constraintTop_toTopOf="@+id/left_text_view" app:layout_constraintBottom_toBottomOf="@+id/left_text_view"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键注意点
- 高度统一:两个视图都设置为
84dp,和Vector Drawable的高度一致,避免背景拉伸变形。 - 无缝贴合:Button默认有内边距,必须设置
android:padding="0dp",同时不要给两个视图加横向margin,确保右侧按钮的左边缘完全贴合左侧TextView的右边缘。 - 对齐约束:用
app:layout_constraintTop_toTopOf和app:layout_constraintBottom_toBottomOf让两个视图的高度完全对齐,不会出现上下错位。
这样就能实现你想要的组合效果啦!
内容的提问来源于stack exchange,提问作者MohammadReza Hosseini
相关产品推荐
相关产品推荐

