Android自定义View中如何通过属性设置调整填充布局尺寸?
如何通过属性设置调整Android自定义填充布局的尺寸?
嗨,我来帮你搞定这个问题!你现在基于FrameLayout实现自定义View,通过LayoutInflater填充布局,想要用自定义属性来控制这个填充布局的尺寸对吧?可以按下面这几步操作:
1. 定义自定义属性
首先在res/values/attrs.xml文件中添加我们需要的自定义属性,用来指定填充布局的宽和高:
<resources> <declare-styleable name="CustomView"> <!-- 自定义填充布局的宽度 --> <attr name="custom_layout_width" format="dimension" /> <!-- 自定义填充布局的高度 --> <attr name="custom_layout_height" format="dimension" /> </declare-styleable> </resources>
2. 在CustomView中解析属性并设置尺寸
修改你的CustomView构造方法,先解析从XML中获取的属性值,然后给填充进来的View设置对应的LayoutParams:
public class CustomView extends FrameLayout { public CustomView(@NonNull Context context) { this(context, null); } public CustomView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public CustomView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // 1. 解析自定义属性 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView); // 获取宽度,默认值设为WRAP_CONTENT int targetWidth = typedArray.getDimensionPixelSize( R.styleable.CustomView_custom_layout_width, LayoutParams.WRAP_CONTENT ); // 获取高度,默认值设为WRAP_CONTENT int targetHeight = typedArray.getDimensionPixelSize( R.styleable.CustomView_custom_layout_height, LayoutParams.WRAP_CONTENT ); // 记得回收TypedArray,避免内存泄漏 typedArray.recycle(); // 2. 填充布局(这里不要直接把this作为父容器传入,否则会自动添加,无法修改LayoutParams) View inflatedLayout = LayoutInflater.from(context).inflate(R.layout.custom_view, this, false); // 3. 设置填充布局的尺寸 inflatedLayout.setLayoutParams(new LayoutParams(targetWidth, targetHeight)); // 4. 将布局添加到当前CustomView中 addView(inflatedLayout); } }
这里要注意:之前的inflate如果直接传this作为第三个参数(attachToRoot),系统会自动把填充的布局添加到父容器,此时再修改LayoutParams可能不生效。所以我们先把attachToRoot设为false,设置好LayoutParams后再手动添加。
3. 在XML布局中使用自定义属性
在使用CustomView的XML文件里,就可以通过自定义属性来控制填充布局的尺寸了,记得要添加自定义命名空间:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" <!-- 这个命名空间必须加 --> android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <com.yourpackage.CustomView android:layout_width="match_parent" android:layout_height="match_parent" app:custom_layout_width="250dp" app:custom_layout_height="180dp" /> </LinearLayout>
如果你的需求是支持match_parent这类相对尺寸,也可以把属性的format改成dimension|enum,然后定义对应的枚举值,不过大多数场景下用dimension格式加上默认的WRAP_CONTENT就足够啦。
内容的提问来源于stack exchange,提问作者Leap Bun
相关产品推荐
相关产品推荐

