【发布时间】:2019-12-20 12:18:11
【问题描述】:
我有一个布局 xml 文件,其中包含一个带有 2 个子 LinearLayouts 的 LinearLayout。 我想分离孩子,所以我将它们放在 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>
【问题讨论】:
-
使用整数关系作为权重...你显然希望一个是另一个的四分之一,所以给它一个权重
1,另一个权重4。可能还需要定义父对象的方向。 -
@deHaar 仍然没有显示任何东西,我已经按照你说的改变了权重,在问题中添加了我父母 LL 的代码
-
您还需要设置子布局的布局参数。在您的代码中,我可以看到设置
layoutParams仅适用于父母。 -
podView和podViewDate需要在它们上设置LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, ??),其中??是每个的权重(作为小数完全可以)。如果podViewWrapper本身位于另一个LinearLayout中,则podViewWrapper将只有LinearLayout.LayoutParams。您还需要将podViewWrapper添加到屏幕上的某个ViewGroup才能看到它,但是您没有显示这是如何发生的或发生在何处,因此我们无法判断那里是否存在问题。顺便说一句,LinearLayouts 默认是水平的,所以你不需要明确地设置它。 -
Mike M. 和 Ircover,感谢兄弟们的帮助,它现在可以正常工作了 :)
标签: android kotlin android-linearlayout android-layout-weight