Android:使用 addView 时会忽略 match_parent

标签 android layout

在我的应用程序中,我使用 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/

相关文章:

html - 使一个元素在单独时居中,但在与另一个元素一起时向右对齐

java - 如何占用Eclipse UI中的可用空间?

android - 图像在android中的gridview中重叠

android - 如何使用 Ionic 更改 Android 主题浏览器中的状态栏颜色?

java - Actionbar home/up button actual id 不同于 R.id.home

javascript - D3 Streamgraph 中 stack.values([accessor]) 的正确用法?

android - 为每条记录重复一个复杂的Layout

html - 将我的页面分成 2 个垂直列(html 或 css)

java - 禁用 GoogleAnalytics 以测试和开发新版本

浏览器中的 Android 模拟器