【问题标题】:How can I change the image of an ImageView? [duplicate]如何更改 ImageView 的图像? [复制]
【发布时间】:2011-07-02 15:17:18
【问题描述】:

我刚开始学习安卓。而且我不知道如何更改ImageView 的图像?即它有一些在布局中设置的图像,但我想通过编码更改该图像我应该怎么做?

这是xml文件

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
 >

<ImageView
  android:id="@+id/image"
  android:layout_width="50dip"
  android:layout_height="fill_parent" 
  android:src="@drawable/icon"
  android:layout_marginLeft="3dip"
  android:scaleType="center"/>

感谢回复。

【问题讨论】:

  • 您能否说得更清楚一些,在您的问题中,我认为您可能希望在 imageView 中动态显示图像,例如,当我触摸并滑动时,必须显示下一张图像,对吗?

标签: android android-imageview


【解决方案1】:

如果您使用 xml 文件创建了 imageview,请按照以下步骤操作。

解决方案一:

第 1 步:创建 XML 文件

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
  >

  <ImageView
      android:id="@+id/image"
      android:layout_width="50dip"
      android:layout_height="fill_parent" 
      android:src="@drawable/icon"
      android:layout_marginLeft="3dip"
      android:scaleType="center"/>

</LinearLayout>

第 2 步:创建一个 Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

解决方案 2:

如果你从 Java 类创建了 imageview

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);

【讨论】:

    【解决方案2】:

    看看ImageView API。有几种setImage* 方法。使用哪一个取决于您提供的图像。如果您将图像作为资源(例如文件 res/drawable/my_image.png)

    ImageView img = new ImageView(this);  // or (ImageView) findViewById(R.id.myImageView);
    img.setImageResource(R.drawable.my_image);
    

    【讨论】:

    • 我可以通过图像视图更改屏幕颜色吗
    • 您正在链接到您电脑上的 API 文档 :)
    • Uups - 固定链接。感谢您的信息!
    • @Uttam:我希望你使用了一个布局,将背景颜色设置为布局,它将出现在你的屏幕上
    • 不要使用 cmets 提问 - 没有人会找到他们,你不能接受正确的答案。
    【解决方案3】:

    只是稍微深入一点,你也可以直接设置位图,像这样:

    ImageView imageView = new ImageView(this);  
    Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
    imageView.setImageBitmap(bImage);
    

    当然,这种技术只有在您需要更改图像时才有用。

    【讨论】:

      【解决方案4】:
      if (android.os.Build.VERSION.SDK_INT >= 21) {
                  storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
      } else {
                  storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-30
        • 1970-01-01
        相关资源
        最近更新 更多