如何在 C# 中的 Android Xamarin 中从代码后面设置按钮的布局宽度?

How to set layout width of a button from code behind in Android Xamarin in C#?

我正在 Xamarin Android C# 项目中使用 Android 按钮。

<Button          
android:id="@+id/btn1"          
android:layout_width="120dp"          
android:layout_height="120dp"          
android:background="@drawable/ButtonImages"          
android:layout_marginLeft="35dp"   />     

这里我想设置这个 Android: layout_width="120dp"Android: layout_marginLeft="35dp" 来自后面的代码。

我通过

从后面的代码中获得了按钮控件
Button btn1 = FindViewById<Button>(Resource.Id.btn1);

但无法设置widthmarginLeft

我该怎么做?

尚未测试这是 xamarin,但理想情况下,这应该可以工作,请尝试并更新。在这里,我已经设置了高度和重量为120dp,你可以根据自己的需要进行修改。也可以通过替换文本来根据需要设置边距。

Button btn1 = FindViewById<Button>(Resource.Id.btn1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams (120,120);
params.setMargins(left, top, right, bottom);
btn1.setLayoutParams(params);