如何使用Java代码在Android中显示图像

如何使用Java代码在Android中显示图像,android,Android,我正在尝试使用java代码而不是xml在android中显示图像。 我已经使用xml文件完成了,但我的要求是使用 java代码以获得更多功能性 提前感谢您的帮助……。使用Drawable类,您可以显示图像 Drawable drawable = Drawable.createFromPath(imagePath); image.setImageDrawable(drawable); 如果要从drawable文件夹加载图像,可以使用: ImageView imgView=(ImageView

我正在尝试使用java代码而不是xml在android中显示图像。 我已经使用xml文件完成了,但我的要求是使用 java代码以获得更多功能性


提前感谢您的帮助……。

使用Drawable类,您可以显示图像

Drawable  drawable  = Drawable.createFromPath(imagePath);
image.setImageDrawable(drawable);

如果要从drawable文件夹加载图像,可以使用:

ImageView imgView=(ImageView) findViewById(R.id.imgView);
Drawable  drawable  = getResources().getDrawable(R.drawable.img);
imgView.setImageDrawable(drawable);

我希望您正在使用ImageView以id为iv的XML文件显示图像

在java文件中

ImageView iv = (ImageView)findViewById(R.id.iv);
iv.setImageResource(R.drawable.image1); // image1 is image file available in drawables folder

使用ImageView并从这里了解更多信息


您可以从位图、uri、资源等设置图像。

当您运行应用程序时,您必须在android xml中使用一个默认图像视图 在“活动”中,您必须编写此代码,以便用另一个图像替换您的图像。 检查以下代码

ImageView imgView=(ImageView) findViewById(R.id.default_imgView);
imgView.setImageResource(R.drawable.yourimagename);
 ImageView img = new ImageView(this);  /*In new version of Android Studio you don't need to do castling.*/
    img = findViewById(R.id.android_image);
    Drawable img_drawable=getResources().getDrawable(R.drawable.draw_img);
    img_cookie.setImageDrawable(img_drawable);

首先将图像添加到可绘制文件夹 并使用XML图像视图

 image = (ImageView) findViewById(R.id.imageView1);
  image.setImageResource(R.drawable.image_1);
  image.setImageResource(R.drawable.image_2);
  ..

您可以使用以下代码

ImageView imgView=(ImageView) findViewById(R.id.default_imgView);
imgView.setImageResource(R.drawable.yourimagename);
 ImageView img = new ImageView(this);  /*In new version of Android Studio you don't need to do castling.*/
    img = findViewById(R.id.android_image);
    Drawable img_drawable=getResources().getDrawable(R.drawable.draw_img);
    img_cookie.setImageDrawable(img_drawable);

下面的代码对我很有效

ImageView imageViewVar = (ImageView) findViewById(R.id.imageViewId);
imageViewVar.setImageResource(R.drawable.yourImgFile);

您可以发布代码并向我们展示您拥有的和想要更改/添加的内容吗?虽然此代码可能会解决问题,但如何以及为什么解决此问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。