如何更改 ImageView 的图像?

我刚刚开始学习机器人。我不知道如何改变 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"/>

谢谢你的回复。

498154 次浏览

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

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

如果您使用 xml 文件创建了 image view,那么按照下面的步骤操作。

解决方案1:

步骤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: 创建一个活动

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

解决方案2:

如果您从 Java 类创建了 image 视图

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

为了更进一步,你也可以直接设置一个位图,像这样:

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

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

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]));
}