繁体   English   中英

如何使用图库允许用户从应用程序的res / drawable中选择资源?

[英]How can I use Gallery to allow user to pick a resource from res/drawable in app?

我以前在我的应用程序中使用过android画廊,允许用户从SD卡中选择图片(使用下面的代码)。

我的问题是:我该怎么做,但允许用户选择存储在我的应用程序/ res / drawable目录中的图像?

使用图库从SD中选取的代码:

Intent i = new Intent(Intent.ACTION_PICK,
               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE); 

然后在onActivityForResult中,调用intent.getData()以获取图像的Uri。

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
        }
    }
}

尽管这不是最佳解决方案,但看起来我可能必须像本教程一样编写自己的画廊视图:

mgmblog.com/2008/12/12/listing-androids-drawable-resources

更新:链接早已失效,但是下面的相关代码使我可以迭代我的应用程序res可绘制对象:

Field[] drawables = com.example.appname.R.drawable.class.getFields();
  for (Field f : drawables) {
    try {
        System.out.println("com.example.appname.R.drawable." + f.getName());
    } catch (Exception e) {
        e.printStackTrace();
    }
  }

其中com.example.appname是您的应用程序名称空间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM