【问题标题】:Populate Android Gallery from image file paths?从图像文件路径填充 Android 图库?
【发布时间】:2012-01-31 19:39:32
【问题描述】:

当应用程序启动时,我有一些图像保存到 Android 设备上的目录中——我希望能够在图库中显示这些图像,但到目前为止我还没有做到。

我遵循示例库代码here,但它使用可绘制资源 ID 而不是文件路径。我发现 this solution 与我正在寻找的类似,只是它使用 ImageView 而不是 Gallery。

所以使用 ImageView 的代码看起来像这样:

File imgFile = new  File(“/data/data/com.myproject.example/files/someImage.png”);
if(imgFile.exists()){

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

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

}

上面的代码有效,但我不知道如何使用画廊来做到这一点。我一直在寻找答案并尝试不同的事情,但我是 Android 开发的新手,我觉得我有点过头了。

感谢任何帮助。提前谢谢你。

【问题讨论】:

    标签: android dynamic path image-gallery


    【解决方案1】:

    基本上我认为您只需将两个示例放在一起即可。

    使用 HelloGallery 示例作为开始,但是您希望将 ImageAdaptergetView() 方法内的代码更改为在 ImageView 上调用 setImageBitmap() 而不是 setImageResource()

    您将需要一个要加载的图像文件路径的数组/集合。

    【讨论】:

      【解决方案2】:

      你需要做的是这样的:

      public ImageAdapter(Context c, int itemId) {
          context = c;
      
          imgArr = GlobalStore.getItem(itemId).getPhotos();
          TypedArray attr = context.obtainStyledAttributes(R.styleable.HelloGallery);
          mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
          attr.recycle();
      }
      

      如您所见,这基本上是图库教程的副本。在构造函数 imgArr 变量中加载了一个 JPG 文件名数组。例如,这些是从数据库中读取的。

      然后在 getView 函数中你有这样的东西......

          public View getView(int position, View convertView, ViewGroup parent) {
          ImageView imageView = new ImageView(context);
      
      
          String tmpStr = appContext.getFilesDir() + File.separator + "photos" + File.separator + imgArr.get(position);
          Bitmap bitmap = BitmapFactory.decodeFile(tmpStr);
          imageView.setImageBitmap(bitmap);
          imageView.setLayoutParams(new Gallery.LayoutParams(350, 300));
          imageView.setScaleType(ImageView.ScaleType.FIT_XY);
          imageView.setBackgroundResource(mGalleryItemBackground);
      
          return imageView;
      }
      

      如您所见,getFilesDir() 获取应用程序数据存储文件的位置,然后让我们假设所有照片都在“照片”目录中,您构建一个路径并从 imgArr附加一个文件名> 阵列。由于每张照片都会调用它,因此您只需使用传递的 position 变量。

      如果您没有照片数组,那么可能的方法是通过读取存储照片的目录来构建它,将所有文件名加载到一个数组中,然后执行此操作。

      然后,您可以像在画廊教程中一样在画廊一侧完成其余的工作。

      【讨论】:

        猜你喜欢
        • 2019-05-05
        • 1970-01-01
        • 2019-07-06
        • 1970-01-01
        • 1970-01-01
        • 2011-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多