Share via


How to dynamically set the width/height of an image view?

Question

Thursday, December 26, 2019 12:31 AM

When I created the predefined Image View I simply dragged the sides to choose the dimensions. How can I achieve the same programmatically? I've tried but I think the problem is that the param's height is set to ViewGroup.LayoutParams.WrapContent, which means it takes up the entirety of the screen as there is no Image Views already in place?

Here is my following code:

        foreach (var item in table)
        {
            Component pullComponent = new Component(item.CategoryName, item.Name, item.Price, item.Id);

            //Create screen layout programically
            //root layout
            LinearLayout LL = FindViewById<LinearLayout>(Resource.Id.mainLinearLayout);

            //Parameter
            //Create relative layout
            var param = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);

            //Create image view
            var iV = new ImageView(this);
            //Get resource id
            var mydrw = (int)typeof(Resource.Drawable).GetField("defaultCase").GetValue(null);
            //Set the image resource as the resource id
            iV.SetImageResource(mydrw);
            //Set the image dimensions
            iV.SetMaxWidth(50);

            //Add the image view inside the param and the param to the root LinearLayout
            LL.AddView(iV, param);

Thank you

All replies (1)

Thursday, December 26, 2019 3:08 AM

How did you set up your relative layout? If it has a larger height than the screen the other controls won't be displayed as they will be located outside of the screen. Try to use a scroll view to confirm this. Make your parent linear layout wrapped by a scroll view like:

<ScrollView android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:fillViewport="true" 
            xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout 
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mainLinearLayout">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="1000dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Test"/>
        </RelativeLayout>

    </LinearLayout>
</ScrollView>

I manually set the relative layout's height to 1000 to simulate your environment and the image view which is created in code behind will be displayed at the end of the screen: Moreover, the LL is a linear layout so change the param to:

var param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);