繁体   English   中英

如何更改以编程方式添加的图像大小

[英]How to change the image size added programmatically

我有一个LinearLayout ,当我单击按钮时添加图像,我试图使用LayoutParams来更改宽度和高度,因为不符合应有的要求,而且我总是得到一个空引用,问题是我不能做任何参考,因为不是静态ImageView

这就是我在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>

首先你必须找到你在linearlayout中添加的Imageview并设置大小即

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

您正在动态创建 ImageView,因此您必须首先为其设置 layoutParameters,然后才能设置 imageview 的高度和宽度。 设置 LayoutParams问题时参考此NullPointerException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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