如何将 2 个具有权重属性的线性布局与父线性布局分开



我有一个布局xml文件,其中包含一个LinearLayout,其中包含2个子LinearLayouts。 我想将子项分开,以便将它们放在 2 个布局 xml 文件中,然后在 Kotlin 代码中定义父 LinearLayout 并将子项添加到其中。如果这是正确的方法,请纠正我。

问题是第一个 LinearLayout 子项的权重为 0.2,第二个子项的权重为 0.8。因此,当我将它们添加到 Kotlin 中定义的父 LinearLayout 时,它会返回一个空项。

这就是我在 Kotlin 中定义父 LinearLayout 的方式:

val podView = LayoutInflater.from(parent.context).inflate(R.layout.first_item, parent, false)
val podViewDate = LayoutInflater.from(parent.context).inflate(R.layout.second_item, parent, false)
val podViewWrapper = LinearLayout(parent.context)
val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
podViewWrapper.layoutParams = params
podViewWrapper.orientation = LinearLayout.HORIZONTAL
podViewWrapper.addView(podViewDate)
podViewWrapper.addView(podView)
podViewWrapper.setDividerPadding(30)

这是我想要分离的文件 - profile_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="12dp"
>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:background="#000"
android:orientation="vertical"
>

<TextView
android:id="@+id/dayNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="6"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold"
/>
<TextView
android:id="@+id/dayName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sun"
android:textColor="#fff"
android:textSize="16sp" />
</LinearLayout>

<LinearLayout
android:id="@+id/numberBar"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:background="@drawable/rounded_corner"
>
<TextView
android:id="@+id/numberBarText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:gravity="center_vertical"
android:text="6"
android:textColor="#fff"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>

您的父布局没有任何方向,因此请添加方向

您的父布局应如下所示

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="12dp"
>

如果您希望您的孩子并排查看,请设置方向

android:orientation="horizontal"

最新更新