简体   繁体   中英

Array with images from drawable and intent

I have a list of images:

private int[] images = {
        R.drawable.blue_icon_left_foot,
        R.drawable.blue_icon_right_foot,
        R.drawable.blue_icon_left_hand,
        R.drawable.blue_icon_right_hand,
        R.drawable.green_icon_left_foot,
        R.drawable.green_icon_right_foot,
        R.drawable.green_icon_left_hand,
        R.drawable.green_icon_right_hand,
        R.drawable.red_icon_left_foot,
        R.drawable.red_icon_right_foot,
        R.drawable.red_icon_left_hand,
        R.drawable.red_icon_right_hand,
        R.drawable.yellow_icon_left_foot,
        R.drawable.yellow_icon_right_foot,
        R.drawable.yellow_icon_left_hand,
        R.drawable.yellow_icon_right_hand};

I want to let the user pick an image from the gallery by using an Intent:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

One of the images of the array should then be replaced with the new image given by the user. When I get the image from the user, I only have a URI of the image:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == 1) {
        Uri imageUri = data.getData();
        //Insert image into images list
    }
}

Is it possible to somehow get an integer ID of the image so that I can insert the image into the same list as the images from the drawable folder? Or should I instead try to store a list of URI's (if it is possible to get URI's of the images from the drawable folder)? Or is there a third solution that is completely different and much better?

You can generate ids with View.generateViewId() if you are using API 17 or larger.

From the main documentation:

Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.

Returns a generated ID value

You can check this answer to see what are the alternatives when you are using a lower API: Android: View.setID(int id) programmatically - how to avoid ID conflicts?

I think what you are trying to do is somewhat misguided. The resources in the /res directory are compile time resources that you bundle with your project. The image that a person selects via an intent from their device is a run time file that will vary by user, device, etc. You are better off not trying to treat them the same. Save the user selections as dataUris or strings and keep the resources as ints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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