[英]How does layout_width/height work together with min/max width/height
[英]How do you set layout_width/height from View constructor
在RecyclerView
,我正在創建新的CustomView
,然后設置其Layout參數,如下所示:
@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布局中使用,因此不必遵循標准構造,但是默認構造函數可能會對setLayoutParams
所做的其他事情使用XML layout_width/height
。
根據版式,屬性和您博客文章 :
要逐個子地更改內容,布局使用
layout_
屬性形式的layout_
一種機制,將其添加到子視圖中。 這些屬性是不同的,因為layout_
屬性是父ViewGroup的指令 ,而不是View本身的指令 。
因此,您的CustomView不會將布局參數傳遞給您-它們會傳遞給您將CustomView添加到的任何布局。 然后,父布局將使用這些值來度量和布局 CustomView。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.