在我的应用程序中,我使用addView动态地向布局添加视图.
添加的视图预先使用膨胀
andorid:layout_width="match_parent"
Run Code Online (Sandbox Code Playgroud)
但是,在添加视图后使用
parentView.addView(view, index);
Run Code Online (Sandbox Code Playgroud)
视图是添加的,但是不要填充父级的宽度
我猜这是因为"视图膨胀"时预先完成对"match_parent"大小的计算,因此它没有参考如何设置corect宽度
是这个案子?
有没有办法告诉视图重新计算布局参数?
我的代码:
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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
Tx的帮助:)
Dmy*_*lyk 13
好的,只需添加此代码即可
View aiv = findViewById(R.id.placeHolder);
aiv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)
马克已经解决了.