从 C# 为 LinearLayout 设置 android:layout_weight



I have LinearLayout

<LinearLayout
android:id="@+id/profile_buttons_view"
android:layout_marginBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_alignParentBottom="true">

我通过 Id 在我的代码中找到了它

linearLayoutProfile = FindViewById<LinearLayout>(Resource.Id.linear_layout_profile);

例如,可见的属性正在工作。它是真正的组件,C#找到了它。但是我需要将 android:layout_weight 更改为 - 2。我这样做

linearLayoutProfileButtonsView.WeightSum = 2; 

但它不起作用。我该怎么做?

您可以从代码访问任何LayoutParams。你只需要非常清楚你的访问是什么布局参数。这通常是通过检查包含的 ViewGroup 来实现的,如果它有一个 LayoutParams 内部子级,那么这就是你应该使用的子级。在您的情况下,它是 线性布局 .布局参数。

检查以下代码:

LinearLayout linearLayoutProfile = FindViewById<LinearLayout>(Resource.Id.linear_layout_profile);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MatchParent,
LayoutParams.MatchParent,
2f   //set layout_weight here
);
linearLayoutProfile.LayoutParameters = param;

实际上,正确的方法是在构造函数中传递它,如下所示:

linearLayoutProfile.LayoutParameters = new LinearLayout.
LayoutParam ( ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.MatchParent, 1f); // 1f here is the weight

注意事项:

  • 权重应始终作为浮点值给出。

  • 分配给任何控件的布局参数应始终基于其父控件,因此,例如,如果linearLayoutProfile的父控件RelativeLayout,则应在上面的示例中使用"RelativeLayout"的布局参数。

古德勒克

在遇到任何查询时还原

最新更新