以编程方式更改android中ImageView的背景/来源

问题描述 投票:0回答:3

我正在创建一个Android应用,我想在其中全屏显示图像。该图像存储在android手机的内部存储器中,并且每次显示的图像都会有所不同。在该活动的布局XML文件中,我添加了一个图像视图标签,如下所示:

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/android" />

android:src我应该输入什么?任何帮助和建议,将不胜感激。

android android-imageview android-file android-bitmap
3个回答
3
投票

可选:删除行

android:src="@drawable/android"
//This can be kept as a default image in case the file you want does not exist.

来自XML布局。由于图像可能每次都不同,因此您需要使用

File file = new  File("/sdcard/Images/test_image.jpg");

if(file.exists()){

    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

    ImageView image = (ImageView) findViewById(R.id.imageview1);

    image.setImageBitmap(bitmap);

}

2
投票

尝试下面的代码从SD卡中存储的文件中设置位图图像。

File imgFile = new  File("/sdcard/Images/test_image.jpg");

if(imgFile.exists()){

    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

    myImage.setImageBitmap(myBitmap);

}

这在运行时有效


1
投票

您可以在运行时执行此操作,请尝试以下操作:

String pathName = "/sdcard/abc.png";
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
BitmapDrawable bd = new BitmapDrawable(res, bitmap);
ImageView view = (ImageView) findViewById(R.id.container);
view.setBackgroundDrawable(bd);
© www.soinside.com 2019 - 2024. All rights reserved.