简体   繁体   中英

How to change the image size added programmatically

I have a LinearLayout which I add images when i click a button, I was trying to use LayoutParams to change the width and height because doesn't fit as at should, and I always got a null reference, the problem is I can't make any reference because is not a static ImageView .

This is how I add images inside of LinearLayout :

public void AddNewImages(Context context,Bitmap bitmap){
    ImageView img = new ImageView(context);
    img.setScaleType(ImageView.ScaleType.FIT_XY);
    img.setImageBitmap(bitmap);
    linearImages.addView(img);
    bitmapArray.add(bitmap);
    indexTags++;
}

XML :

<LinearLayout
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <HorizontalScrollView
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <LinearLayout
            android:orientation="horizontal"
            android:id="@+id/linearImages"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <Button
                android:layout_gravity="center"
                android:id="@+id/add_btn"
                android:text="Add"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </HorizontalScrollView>

First you have to find the Imageview which you added in linearlayout and set the size ie

for(int i=0;i<linearImages.getChildCount();i++)
{
    ImageView image=(ImageView)linearImages.getChildAt(i);
    image.getLayoutParams().height=100;
    image.getLayoutParams().width=100;
}
ImageView imgae = (ImageView) linearImages.getChildAt(0); // For first image

然后设置LayoutParam

You are creating ImageView dynamically so you have to first set layoutParameters for it and then you can set height and width of imageview. Refer this NullPointerException while setting LayoutParams question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM