layout_weight以编程方式解释v.



过去两天我一直在研究有关以编程方式设置布局或一组布局权重的问题。

我找到的所有答案几乎都相同,这意味着我知道要使用什么代码 NO,但我似乎不明白如何分配 float 属性。 在下面的代码中。

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
YOUR_VIEW.setLayoutParams(param);

有人可以给我一个例子,说明如何分配两个权重总和为 3 的 TextView 的权重吗???

这取决于您的视图,如果您想在它们之间水平拆分视图,您可以使用这样的东西。

TextView secondTV = findViewById(R.id.secondTextView);
TextView firstTV = findViewById(R.id.firstTextView);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 3);
LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1);
firstTV.setLayoutParams(layoutParams);
secondTV.setLayoutParams(layoutParams1);

你的布局看起来像这样

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/firstTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello" />
<TextView
android:id="@+id/secondTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/icon"
android:text="Hello" />
</LinearLayout>

但是如果你想垂直分割视图,你可以使用这样的东西。

TextView secondTV = findViewById(R.id.secondTextView);
TextView firstTV = findViewById(R.id.firstTextView);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 3);
LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1);
firstTV.setLayoutParams(layoutParams);
secondTV.setLayoutParams(layoutParams1);

你的布局看起来像这样

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/firstTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello" />
<TextView
android:id="@+id/secondTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/icon"
android:text="Hello" />
</LinearLayout>

最新更新