如何使用 Android 自定义视图中设置的属性调整膨胀布局的大小?

How to resize inflated layout with attribute set in Android custom view?

我正在通过从布局中膨胀来创建自定义视图,如下所示:

CustomView.java

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);

        LayoutInflater.from(context).inflate(R.layout.custom_view, this, true);
    }
}

custom_view.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...

</FrameLayout>

我的问题是,当我在具有某些 layout_width 和 layout_height 值的布局中使用此自定义视图时,其中的内容不会根据新值调整大小。

由于您的 CustomView 扩展了 FrameLayout 并且 custom_view.xml 的根也是 FrameLayout,您可以使用 merge.

只需将 custom_view.xml 的根更改为 <merge></merge>