Harmeet Singh Virdi Harmeet Singh Virdi - 4 months ago 11
Android Question

Dynamically loaded ImageView not getting layout_height and layout_width specified in xml file

When i dynamically add ImageView from dynamic_image_view.xml file into linear layout of activity_main.xml, ImageView's layout_height and layout_width are not set according to ImageView in dynamic_image_view.xml file.

Here is link of my output:
https://drive.google.com/file/d/0B6TH-xS6p0y0ZTE5VFpiOUI3R2M/view?usp=sharing

Here is my code:

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup ll = (ViewGroup) findViewById(R.id.ll);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dynamic_image_view,null);
ll.addView(view.findViewById(R.id.dynamic_image));
}
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/ll"
android:orientation="vertical"
tools:context="com.example.harmeet.dynamicimageloadtest.MainActivity">

</LinearLayout>


dynamic_image_view.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="@drawable/images"
android:id="@+id/dynamic_image"
android:scaleType="fitXY"/>

Answer

THe problem is your inflate params- you need to pass it the linear layout as the root if you want all the width/height/margins to correctly parse. And that way you won't need to add it later.

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dynamic_image_view,ll);