经常遇到用LayoutInfater时,发现布局跟xml里写的布局不一样,顶层布局的效果没出来,
比如,要设置 gravity 和 weight 权重 等,
查了很多资料,有说是inflate的时候是默认用一层FrameLayout包住了,
找到的解决办法是,再xml布局文件里多嵌一层布局,来达到控制的目的,感觉这样不是很好,但暂时没有找到好的解决办法,
想着能不能在代码里设置一下父布局,代码如下:
class WeatherItemSmall extends RelativeLayout{
public WeatherItemSmall(Context context) {
super(context);
initView();
}
private void initView() {
LayoutInflater.from(mContext).inflate(R.layout.item_weather_small, this, true);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, Float.parseFloat("1"));
setLayoutParams(params);
setGravity(Gravity.CENTER);
}
}
这样能达到想要的效果,不知道有没有什么不妥,先记录着以后研究。