【问题标题】:How to change the image size added programmatically如何更改以编程方式添加的图像大小
【发布时间】:2017-06-16 14:39:13
【问题描述】:

我有一个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>

【问题讨论】:

  • 从 linearImages 子中获取图像视图

标签: java android


【解决方案1】:

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

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

【讨论】:

  • 我应该把这个放在哪里?在indexTags++; 之后?我试过了,我的应用程序崩溃了,没有给出任何错误
【解决方案2】:
ImageView imgae = (ImageView) linearImages.getChildAt(0); // For first image

然后设置LayoutParam

【讨论】:

    【解决方案3】:

    您正在动态创建 ImageView,因此您必须首先为其设置 layoutParameters,然后您可以设置 imageview 的高度和宽度。参考这个NullPointerException while setting LayoutParams问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 2015-08-10
      相关资源
      最近更新 更多