简体   繁体   English

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

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

I have previously used the android gallery in my app to allow user to select an image from the SD card (using the code below). 我以前在我的应用程序中使用过android画廊,允许用户从SD卡中选择图片(使用下面的代码)。

My question is: How can I do the same, but allow user to select image that is stored in my apps /res/drawable dir? 我的问题是:我该怎么做,但允许用户选择存储在我的应用程序/ res / drawable目录中的图像?

Code for using gallery to pick from SD: 使用图库从SD中选取的代码:

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

Then in onActivityForResult, call intent.getData() to get the Uri of the 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);
        }
    }
}

Although this isn't the best solution, Looks like I may have to write my own gallery view like this tutorial: 尽管这不是最佳解决方案,但看起来我可能必须像本教程一样编写自己的画廊视图:

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

UPDATE: link is long dead, but here is the relevant code that allows me to iterate my apps res drawables: 更新:链接早已失效,但是下面的相关代码使我可以迭代我的应用程序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();
    }
  }

Where com.example.appname is your apps namespace. 其中com.example.appname是您的应用程序名称空间。

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

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