-1

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"/>

2 Answers2

2

Change your

inflater.inflate(R.layout.dynamic_image_view,null);

TO

inflater.inflate(R.layout.dynamic_image_view, parent, false);
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
1

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);
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127