如何在ConstraintLayout中让ProgressBar填充剩余空间?是否需改用LinearLayout?
如何让ProgressBar填充ConstraintLayout剩余空间(无需硬编码宽度)
完全可以在ConstraintLayout里实现这个需求,不用切换到LinearLayout,只需要修改ProgressBar的几个属性即可:
关键修改点
- 把ProgressBar的
android:layout_width设为0dp(对应ConstraintLayout的match_constraint,会自动填充约束之间的剩余空间) - 添加水平方向的边距(
android:layout_marginStart和android:layout_marginEnd)来满足边距需求 - 保留原有的
start和end约束,确保它夹在两个TextView之间
修改后的完整布局代码
<?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="match_parent" android:padding="12dp"> <TextView android:id="@+id/tv_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ProgressBar android:id="@+id/pb_range" style="?android:attr/progressBarStyleHorizontal" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:progress="50" app:layout_constraintEnd_toStartOf="@+id/tv_id2" app:layout_constraintStart_toEndOf="@+id/tv_id" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/tv_id2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
关于LinearLayout的替代方案
如果用LinearLayout也能实现:设置android:orientation="horizontal",给ProgressBar设置android:layout_width="0dp"和android:layout_weight="1",同样能让它填充剩余空间。但ConstraintLayout在处理复杂布局时灵活性更强,当前场景用ConstraintLayout完全足够,没必要切换。
内容的提问来源于stack exchange,提问作者Kamil
相关产品推荐
相关产品推荐

