如何从View构造函数设置layout_width / height

问题描述 投票:0回答:1

RecyclerView中,我正在创建新的CustomViews然后设置它们的布局参数,如下所示:

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    CustomView customView= new CustomView(parent.getContext() /*, ...otherCustomArgs*/);
    customView.setLayoutParams(new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    ));
    // ...
}

现在我已经观察到LinearLayout有很多构造函数 - 我的CustomView扩展的类。

/**
    {@link LinearLayout(Context)}
    {@link LinearLayout(Context, AttributeSet)}
    {@link LinearLayout(Context, AttributeSet, int)}
    {@link LinearLayout(Context, AttributeSet, int, int)}
*/

现在显然有一种标准方法可以在实例化时传递宽度/高度 - 通过这些构造函数之一,这就是将XML布局中的layout_width/height传递给类的方式。

为了保持标准,我想在我的自定义构造函数中使用其中一个,即:

CustomView extends LinearLayout {
    CustomView(Context context, LayoutArgs layoutArgs, Object... otherCustomArgs){
        this(context, ...layoutArgs);
        // Use otherCustomArgs
    }
}

我想,因为这个自定义构造函数实际上永远不会在XML布局中使用,所以没有必要符合标准构造,但是默认构造函数可能还有其他的东西,layout_width/height不会使用XML setLayoutParams

java android android-linearlayout android-custom-view viewgroup
1个回答
1
投票

根据the Layouts, Attributes, and You blog post

为了逐个孩子地改变事物,布局使用layout_属性形式的不同机制,这些机制被添加到子视图中。这些属性是不同的,因为layout_属性是父ViewGroup的指令,而不是View本身的指令。

因此,您的CustomView不会传递给您的布局参数 - 它们会传递给您添加CustomView的任何布局。然后,父布局将使用这些值来measure and layout您的CustomView。

© www.soinside.com 2019 - 2024. All rights reserved.