Search code examples
javaandroid-studioimageviewhorizontalscrollview

Set width and height based on dimentions of parent's parent Android Studio


I'm dynamicly adding ImageViews in a LinearLayout witch is inside a HorizontalScrollView.

Now I want to set the width and height of these ImageViews based on the parent LinearLayout of this HorizontalScrollView.

This is my xml (information_imagescrollview_item.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parentlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    android:paddingBottom="5dp">
    <HorizontalScrollView
        android:id="@+id/horizontal_scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:id="@+id/linear"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal" >
        </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>

and this is my code:

View contentView = inflater.inflate(R.layout.information_imagescrollview_item, container, false);
LinearLayout scrollViewLayout = (LinearLayout) contentView.findViewById(R.id.linear);
for(Object intObj : page.content) {
    ImageView imageView = new ImageView(this.getContext());
    Drawable myDrawable = getResources().getDrawable((int) intObj);
    imageView.setImageDrawable(myDrawable);
    scrollViewLayout.addView(imageView);
}
page.addView(contentView);

How can I set each imageView to have the same width and height as the parentlayout in the xml?


Solution

  • It is possible to change a dynamic view's dimensions by code. So I would bet you should change the ImageView's layout parameters in the for loop before adding it to your LinearLayout like this:

    for(Object intObj : page.content) {
        ImageView imageView = new ImageView(this.getContext());
        Drawable myDrawable = getResources().getDrawable((int) intObj);
        imageView.setImageDrawable(myDrawable);
        //Changing height...
        imageView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
        //...and width
        imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
        scrollViewLayout.addView(imageView);
    }
    

    This will set the ImageView's width and height to the containing (parent) LinearLayout's width and height.