在RecyclerView
中,我正在创建新的CustomView
s然后设置它们的布局参数,如下所示:
@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
。
根据the Layouts, Attributes, and You blog post:
为了逐个孩子地改变事物,布局使用
layout_
属性形式的不同机制,这些机制被添加到子视图中。这些属性是不同的,因为layout_
属性是父ViewGroup的指令,而不是View本身的指令。
因此,您的CustomView不会传递给您的布局参数 - 它们会传递给您添加CustomView的任何布局。然后,父布局将使用这些值来measure and layout您的CustomView。