如果壹個View沒有set?LayoutParams,在該View被添加到壹個ViewGroup裏時,ViewGroup會為該View創建壹個默認的LayoutParams。所以如果題中的view已經存在於壹個ViewGroup中,view.getLayoutParams()便會得到ViewGroup為其創建的默認LayoutParams。而這個默認LayoutParams會因ViewGroup而變,這就看是什麽ViewGroup了。
看下源碼就知道了:
1.ViewGroup.addView
public?void?addView(View?child,?int?index)?{if?(child?==?null)?{
throw?new?IllegalArgumentException("Cannot?add?a?null?child?view?to?a?ViewGroup");
}
LayoutParams?params?=?child.getLayoutParams();
if?(params?==?null)?{
params?=?generateDefaultLayoutParams();
if?(params?==?null)?{
throw?new?IllegalArgumentException("generateDefaultLayoutParams()?cannot?return?null");
}
}
addView(child,?index,?params);
}
2.FrameLayout.generateDefaultLayoutParams
protected?LayoutParams?generateDefaultLayoutParams()?{return?new?LayoutParams(LayoutParams.MATCH_PARENT,?LayoutParams.MATCH_PARENT);
}
3.LinearLayout.generateDefaultLayoutParams
protected?LayoutParams?generateDefaultLayoutParams()?{if?(mOrientation?==?HORIZONTAL)?{
return?new?LayoutParams(LayoutParams.WRAP_CONTENT,?LayoutParams.WRAP_CONTENT);
}?else?if?(mOrientation?==?VERTICAL)?{
return?new?LayoutParams(LayoutParams.MATCH_PARENT,?LayoutParams.WRAP_CONTENT);
}
return?null;
}