如何在Xamarin中以编程方式为EditText等View设置布局属性
Xamarin.Android 动态设置EditText属性实现方案
核心说明
布局相关属性(宽、高、权重)不能直接通过控件自身的SetWidth/SetHeight方法设置,这类方法仅支持固定像素值,需要通过对应父布局的
LayoutParams类配置match_parent、wrap_content和权重这类布局属性。
完整实现代码
// 1. 创建EditText实例 var editText = new EditText(this); // 2. 配置布局参数,此处假设父容器为LinearLayout(只有LinearLayout支持layout_weight属性) var layoutParams = new LinearLayout.LayoutParams( width: ViewGroup.LayoutParams.MatchParent, // 对应 android:layout_width="match_parent" height: ViewGroup.LayoutParams.MatchParent // 对应 android:layout_height="match_parent" ) { Weight = 1f // 对应 android:layout_weight="1" }; editText.LayoutParameters = layoutParams; // 3. 设置ID,两种方式二选一: // 方式1:动态生成唯一ID(无需提前定义id资源,适配API 17及以上版本) editText.Id = View.GenerateViewId(); // 方式2:使用提前在Resources/values/ids.xml中定义的test资源ID,和XML写法完全一致 // editText.Id = Resource.Id.test;
属性对应映射表
android:layout_width="match_parent"→LayoutParams.Width = ViewGroup.LayoutParams.MatchParentandroid:layout_height="match_parent"→LayoutParams.Height = ViewGroup.LayoutParams.MatchParentandroid:layout_weight="1"→LinearLayout.LayoutParams.Weight = 1fandroid:id="@+id/test"→editText.Id = Resource.Id.test或动态生成ID
注意事项
- 如果你的父容器不是LinearLayout,请替换
LinearLayout.LayoutParams为对应父布局的LayoutParams实现类,比如RelativeLayout.LayoutParams、ConstraintLayout.LayoutParams,此时weight属性不会生效,因为weight是LinearLayout专属属性。 - 只有需要设置固定像素宽度时,才可以直接使用
editText.SetWidth(像素值)方法。
内容的提问来源于stack exchange,提问作者sulabh
相关产品推荐
相关产品推荐

