在我的应用程序中,我使用 addView 向布局动态添加 View 。
添加的 View 是预先使用
andorid:layout_width="match_parent"
但是,在使用添加 View 之后
parentView.addView(view, index);
View 已添加但未填充父级的宽度
我猜这是因为“match_parent”大小的计算是事先完成的,
当 View 膨胀时,因此它没有关于如何设置正确宽度的引用
是这样吗?
有没有办法告诉 View 重新计算布局参数?
我的代码:
Activity .xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue_bg">
<ImageView android:id="@+id/myImg"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:src="@drawable/myImg"
android:scaleType="fitXY"/>
<LinearLayout android:id="@+id/addressItemContainer"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_below="@id/myImg" android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<View android:id="@+id/placeHolder"
android:layout_width="match_parent" android:layout_height="match_parent"/>
</LinearLayout>
</RelativeLayout>
inserted_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:background="@drawable/blue_selector">
.... internal views
</LinearLayout>
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:使用 addView 时会忽略 match_parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8201685/