在我的应用程序中,我使用addView动态地向布局添加视图.
添加的视图预先使用膨胀
andorid:layout_width="match_parent"
但是,在添加视图后使用
parentView.addView(view, index);
视图已添加,但不会填充父级的宽度
我想这是因为“match_parent”大小的计算是事先完成的,
当视图膨胀时,因此它没有参考如何设置corect宽度
是这样的吗?
有没有办法告诉视图重新计算布局参数?
我的代码:
activity.xml:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue_bg">
android:layout_width="match_parent" android:layout_height="wrap_content"
android:src="@drawable/myImg"
android:scaleType="fitXY"/>
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_below="@id/myImg" android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
android:layout_width="match_parent" android:layout_height="match_parent"/>
inserted_view.xml:
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:background="@drawable/blue_selector">
.... internal views
java代码:
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.inserted_view, null);
... fill inserted view fields ...
View aiv = findViewById(R.id.placeHolder);
ViewGroup parent = (ViewGroup) aiv.getParent();
int index = parent.indexOfChild(aiv);
parent.removeView(aiv);
parent.addView(view, index);
Tx的帮助:)
解决方法:
好的,只需添加此代码即可
View aiv = findViewById(R.id.placeHolder);
aiv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
马克已经解决了.
标签:android,layout
来源: https://codeday.me/bug/20190714/1462232.html