Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: match_parent is ignored when using addView

Tags:

android

layout

In my application I'm adding a view dynamically to the layout using addView.
The added view was inflated beforehand using

andorid:layout_width="match_parent"  

however, after the adding the view using

parentView.addView(view, index);  

The view is addded but dosen't fill the parent's width
I guess this is because the calculation to the "match_parent" size is done beforehand, when the view is inflated, and therefore it has no reference of how to set the corect width
is this the case?
is there a way for me to tell the view to recalculate the layout params?

my Code:
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 code:

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 for the help :)

like image 554
Tomer Avatar asked Nov 20 '11 13:11

Tomer


2 Answers

Ok, just add this code

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

Mark as resolved, please.

like image 161
Dmytro Danylyk Avatar answered Oct 22 '22 22:10

Dmytro Danylyk


View view = findViewById(R.id.placeHolder);
view .setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//addView(view)

Thanks Dmytro Danylyk. Now its work prefectly.

like image 1
Javad B Avatar answered Oct 23 '22 00:10

Javad B