当前位置: 代码迷 >> Android >> 从图库中获取所有图像并存储在数组中
  详细解决方案

从图库中获取所有图像并存储在数组中

热度:82   发布时间:2023-08-04 12:26:15.0

我有为图像(可绘制)定义的代码,这意味着已经定义了图像,但是我希望用户从Gallery中选择Image。 因此,我首先要从图库中获取所有图像,然后将其显示在视图中,并从其用户中选择Image。

因此,这意味着所有图像必须保存在数组中,如下所示。 任何帮助。

public class StickerSelectActivity extends AppCompatActivity {

    public static final String EXTRA_STICKER_ID = "extra_sticker_id";

    private final int[] stickerIds = {
            R.drawable.abra,
            R.drawable.bellsprout,
            R.drawable.bracelet,
            R.drawable.bullbasaur,
            R.drawable.camera,
            R.drawable.candy,
            R.drawable.caterpie,
            R.drawable.charmander,
            R.drawable.mankey,
            R.drawable.map,
            R.drawable.mega_ball,
            R.drawable.meowth,
            R.drawable.pawprints,
            R.drawable.pidgey,
            R.drawable.pikachu,
            R.drawable.pikachu_1,
            R.drawable.pikachu_2,
            R.drawable.player,
            R.drawable.pointer,
            R.drawable.pokebag,
            R.drawable.pokeball,
            R.drawable.pokeballs,
            R.drawable.pokecoin,
            R.drawable.pokedex,
            R.drawable.potion,
            R.drawable.psyduck,
            R.drawable.rattata,
            R.drawable.revive,
            R.drawable.squirtle,
            R.drawable.star,
            R.drawable.star_1,
            R.drawable.superball,
            R.drawable.tornado,
            R.drawable.venonat,
            R.drawable.weedle,
            R.drawable.zubat
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_sticker_activity);

        //noinspection ConstantConditions
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.stickers_recycler_view);
        GridLayoutManager glm = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(glm);

        List<Integer> stickers = new ArrayList<>(stickerIds.length);
        for (Integer id : stickerIds) {
            stickers.add(id);
        }

        recyclerView.setAdapter(new StickersAdapter(stickers, this));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void onStickerSelected(int stickerId) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_STICKER_ID, stickerId);
        setResult(RESULT_OK, intent);
        finish();
    }

    class StickersAdapter extends RecyclerView.Adapter<StickersAdapter.StickerViewHolder> {

        private final List<Integer> stickerIds;
        private final Context context;
        private final LayoutInflater layoutInflater;

        StickersAdapter(@NonNull List<Integer> stickerIds, @NonNull Context context) {
            this.stickerIds = stickerIds;
            this.context = context;
            this.layoutInflater = LayoutInflater.from(context);
        }

        @Override
        public StickerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new StickerViewHolder(layoutInflater.inflate(R.layout.sticker_item, parent, false));
        }

        @Override
        public void onBindViewHolder(StickerViewHolder holder, int position) {
            holder.image.setImageDrawable(ContextCompat.getDrawable(context, getItem(position)));
        }

        @Override
        public int getItemCount() {
            return stickerIds.size();
        }

        private int getItem(int position) {
            return stickerIds.get(position);
        }

        class StickerViewHolder extends RecyclerView.ViewHolder {

            ImageView image;

            StickerViewHolder(View itemView) {
                super(itemView);
                image = (ImageView) itemView.findViewById(R.id.sticker_image);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int pos = getAdapterPosition();
                        if (pos >= 0) { // might be NO_POSITION
                            onStickerSelected(getItem(pos));
                        }
                    }
                });
            }
        }
    }
}

如果您想在应用程序的库中显示所有可用图像,则不需要它。 您可以使用

private Cursor cc = null;
cc = this.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
                null)

这将使您与图库中可用的文件建立连接。 更详细的答案在这里

如果万一在您的应用程序中有一个图像视图,并且您希望用户单击该图像,然后Android应询问他们是否要从图库/相机中选择图像,则可以按照以下步骤操作:您可以在setOnClickListener上调用selectImage方法ImageView的。

 private void selectImage() {
        final CharSequence[] items = { "Take Photo", "Choose from Library" };
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Update Profile Photograph");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(getActivity());
                if (items[item].equals("Take Photo")) {
                    if(result)
                        cameraIntent();
                } else if (items[item].equals("Choose from Library")) {
                    if(result)
                        galleryIntent();
                }
            }
        });
        builder.show();
    }
private void cameraIntent() {
        Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        File out = Environment.getExternalStorageDirectory();
        out = new File(out, familyMemberId + ".png");
        Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
        takePicture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        startActivityForResult(takePicture, 0);
    }

    private void galleryIntent() {
        Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
        switch(requestCode) {
            case 0:
                if(resultCode == Activity.RESULT_OK){
                    File out = Environment.getExternalStorageDirectory();
                    out = new File(out, familyMemberId + ".png");
                    Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
                    Toast.makeText(getContext(), photoURI.toString(), Toast.LENGTH_LONG).show();
                    imageUri =  photoURI.toString();
                    Glide.with(this).load(imageUri).into(familyMemberProfilePick);
                }

                break;
            case 1:
                if(resultCode == Activity.RESULT_OK){
                    Uri selectedImage = imageReturnedIntent.getData();
                    imageUri =  selectedImage.toString();
                    Glide.with(this).load(imageUri).into(familyMemberProfilePick);
                }
                break;
        }
    }

请不要忘记添加这些

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application ...

 <provider
            android:name=".utility.GenericFileProvider"
            android:authorities="${applicationId}.app.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
....
</application>
  相关解决方案