问题描述
我有这样的看法:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/sample_icon_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:src="@drawable/active_state"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/sample_item_bar_iv"
android:layout_width="128dp"
android:layout_height="1dp"
android:background="@color/brown_grey"
app:layout_constraintBottom_toBottomOf="@id/sample_icon_iv"
app:layout_constraintStart_toEndOf="@id/sample_icon_iv"
app:layout_constraintTop_toTopOf="@id/sample_icon_iv"
/>
<TextView
android:id="@+id/leave_planner_item_date_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="26 march"
app:layout_constraintEnd_toStartOf="@+id/sample_item_bar_iv"
app:layout_constraintStart_toStartOf="@+id/sample_icon_iv"
app:layout_constraintTop_toBottomOf="@+id/sample_icon_iv"
tools:text="26 march" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
我需要将此视图充气X次,并以水平滚动方式显示均匀分布的视图。我尝试在添加到父级之前将权重1添加到膨胀视图中,但似乎仍然无法正常工作。我还面临着栏和下一个图标之间的间距问题。但是,如果我删除空白,则无法将文本居中放置在图标下方。
这就是我希望看到的景色
我该如何实现?
解决方法
在LinearLayout中包装视图。确定您希望它拥有多少个孩子,然后像这样设置它:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="3"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
此示例将创建3个按钮,它们占据屏幕的整个宽度,每个按钮将获得屏幕宽度的1/3。
要以编程方式这样做:
LinearLayout layout = findViewById(R.id.yourLayoutID);
Button b = new Button(); // Or,if you want something more complicated than a simple object,you can do View v = inflater.inflate(R.layout.your_layout,null);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0,ViewGroup.LayoutParams.MATCH_PARENT);
p.weight = 1;
b.setLayoutParams(p);
layout.addView(b);
那是一般想法