【问题标题】:Programmatically change background / source for ImageView in android以编程方式更改 Android 中 ImageView 的背景/源
【发布时间】:2014-11-29 12:43:41
【问题描述】:

我正在创建一个想要全屏显示图像的 android 应用程序。图像存储在安卓手机的内部存储器中,每次显示的图像可能会有所不同。在该活动的布局 XML 文件中,我添加了一个图像视图标记,如下所示:

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

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

【问题讨论】:

  • 使用java代码而不是xml从sd卡设置源代码。

标签: android android-imageview android-file android-bitmap


【解决方案1】:

可选:删除该行

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

}

【讨论】:

  • Remove the line... - 不需要 - 您可以使用它来显示默认图像
  • 没关系。为你们俩+1 - 答案非常相似并且在同一时间给出(所以,我敢肯定没有人从另一个人那里复制)。
【解决方案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);

}

这在运行时有效

【讨论】:

    【解决方案3】:

    你可以在运行时这样做,试试这个:

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

    【讨论】:

      猜你喜欢
      • 2011-03-07
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 2013-05-30
      • 2014-05-01
      相关资源
      最近更新 更多