【问题标题】:Android: match_parent is ignored when using addViewAndroid:使用 addView 时忽略 match_parent
【发布时间】:2020-03-02 15:58:46
【问题描述】:

在我的应用程序中,我使用 addView 将视图动态添加到布局中。
使用

预先对添加的视图进行了膨胀
andorid:layout_width="match_parent"  

然而,在使用添加视图之后

parentView.addView(view, index);  

视图已添加,但未填充父级的宽度
我猜这是因为“match_parent”大小的计算是事先完成的, 当视图膨胀时,因此它没有关于如何设置正确宽度的参考
是这样吗?
有没有办法告诉视图重新计算布局参数?

我的代码:
活动.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 寻求帮助 :)

【问题讨论】:

    标签: android layout


    【解决方案1】:

    好的,只需添加此代码

    View aiv = findViewById(R.id.placeHolder);
    aiv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    

    请标记为已解决。

    【讨论】:

    • 抱歉,没用。我通过在 xml 中的占位符视图中添加一个 stab 视图 parralel 来解决它
    • 不工作,对答案没有解释,对投票者有任何解释吗?
    【解决方案2】:
    View view = findViewById(R.id.placeHolder);
    view .setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    //addView(view)
    

    感谢 Dmytro Danylyk。现在它的工作完美。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2013-11-02
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      相关资源
      最近更新 更多