153

私はちょうどアンドロイドを学び始めました。そして、どうすれば画像を変更でき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"/>

返信ありがとうございます。

4

4 に答える 4

288

xmlファイルを使用してimageviewを作成した場合は、次の手順に従います。

解決策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:解決策2:

Javaクラスからimageviewを作成した場合

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);
于 2011-02-23T10:08:05.160 に答える
44

ImageViewAPIをご覧ください。いくつかのsetImage*方法があります。どちらを使用するかは、提供する画像によって異なります。画像をリソースとして持っている場合(例:ファイルres / drawable / my_image.png)

ImageView img = new ImageView(this);  // or (ImageView) findViewById(R.id.myImageView);
img.setImageResource(R.drawable.my_image);
于 2011-02-23T10:01:42.253 に答える
16

問題をもう少し進めるために、次のようにビットマップを直接設定することもできます。

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

もちろん、この手法は、画像を変更する必要がある場合にのみ役立ちます。

于 2013-12-05T19:50:58.557 に答える
3
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]));
}
于 2016-08-09T15:35:43.683 に答える