【问题标题】:opening camera and gallery from recycler view adapter using OnActivityResult使用 OnActivityResult 从回收器视图适配器打开相机和图库
【发布时间】:2020-07-05 08:19:50
【问题描述】:

我在我的适配器中创建了一个负责编辑头像的部分,我正在使用一个名为 android image cropper 的库,它需要在活动结果上运行,但由于我在适配器类中,它不允许我使用活动方法。我搜索了但我无法理解代码,因为大部分使用活动并且我使用片段。这是我的适配器类(只是它的一部分):

     holder.btn_edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final LayoutInflater inflater=LayoutInflater.from(context);
                        View add_view=inflater.inflate(R.layout.dialog_addcontacts,null);
                        AlertDialog alertDialog=new AlertDialog.Builder(context).create();
                        alertDialog.setView(add_view);
                        final TextInputEditText edt_name=add_view.findViewById(R.id.edt_name);
                        final TextInputEditText edt_phonenumber=add_view.findViewById(R.id.edt_number);
                        byte[] contactimage=phonebookModel.getImage();
                        Bitmap bitmap= BitmapFactory.decodeByteArray(contactimage,0,contactimage.length);
                        final CircleImageView image_profile=add_view.findViewById(R.id.profile_image);
                        Button btn_add=add_view.findViewById(R.id.btn_add);
                        btn_add.setText("change");
                        edt_name.setText(phonebookModel.getName());
                        edt_phonenumber.setText(phonebookModel.getPhonenumber());
                        image_profile.setImageBitmap(bitmap);
                        image_profile.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
CropImage.activity()
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setCropShape(CropImageView.CropShape.OVAL)
                        .setMaxCropResultSize(2500,2500)
                        .setAspectRatio(1,1)
                        .setScaleType(CropImageView.ScaleType.CENTER)
                        .start(getContext(),ContactsFragment.this);

            }
                              
                            }
                        });
     private byte[] imagetobyte(CircleImageView image){
            Bitmap bitmap=((BitmapDrawable) image.getDrawable()).getBitmap();
            ByteArrayOutputStream stream=new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);
            byte[] bytearray=stream.toByteArray();
            return bytearray;
    
        }

这是我的片段:

public class ContactsFragment extends Fragment {

     RecyclerView recyclerView;
     FloatingActionButton floatingActionButton;
     PhoneBookDB phoneBookDB;
    CircleImageView imagebutton;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.contactsfragment,container,false);
        phoneBookDB =new PhoneBookDB(getContext());
        //recycler-contacts
        recyclerView= view.findViewById(R.id.recycler_contacts);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,false));
        List<PhonebookModel> models=phoneBookDB.getalldata();
        Contactsadapter adapter=new Contactsadapter(models,getContext());
        recyclerView.setAdapter(adapter);
        //add-contacts
        floatingActionButton=view.findViewById(R.id.btn_add_contacts);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showdialog();
            }
        });
        return view;
    }

    public void showdialog() {
            final LayoutInflater inflater=LayoutInflater.from(getContext());
            View add_view=inflater.inflate(R.layout.dialog_addcontacts,null);
            final AlertDialog alertDialog=new AlertDialog.Builder(getContext()).create();
            alertDialog.setView(add_view);
            final TextInputEditText edt_name=add_view.findViewById(R.id.edt_name);
            final TextInputEditText edt_phonenumber=add_view.findViewById(R.id.edt_number);
            imagebutton=add_view.findViewById(R.id.profile_image);
            imagebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CropImage.activity()
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setCropShape(CropImageView.CropShape.OVAL)
                        .setMaxCropResultSize(2500,2500)
                        .setAspectRatio(1,1)
                        .setScaleType(CropImageView.ScaleType.CENTER)
                        .start(getContext(),ContactsFragment.this);

            }
        });
            Button btn_add=add_view.findViewById(R.id.btn_add);
            Button btn_cancel=add_view.findViewById(R.id.btn_cancel);
            btn_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!edt_name.getText().toString().isEmpty()&&!edt_phonenumber.getText().toString().isEmpty()) {
                        long i=  phoneBookDB.insertdata(edt_name.getText().toString(), edt_phonenumber.getText().toString(),imagetobyte(imagebutton));
                        Toast.makeText(getContext(), i+"", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(getContext(), MainActivity.class));
                    }else {
                        Toast.makeText(getContext(), "لطفا تمامی فیلد های خواسته شده را پر کنید", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                }
            });
            alertDialog.show();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();

                try {
                    InputStream inputStream= getActivity().getContentResolver().openInputStream(resultUri);
                    imagebutton.setImageBitmap(BitmapFactory.decodeStream(inputStream));

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }


            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }
    private byte[] imagetobyte(CircleImageView image){
            Bitmap bitmap=((BitmapDrawable) image.getDrawable()).getBitmap();
            ByteArrayOutputStream stream=new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);
            byte[] bytearray=stream.toByteArray();
            return bytearray;

    }

【问题讨论】:

    标签: java android android-studio android-recyclerview


    【解决方案1】:

    根据我目前通过阅读您的问题的理解,我假设您希望使用 CropImage.activity()... 开始库活动,并在 Fragment 中使用 onActivityResult 获得裁剪结果。

    为了在 Fragment 中使用 onActivityResult 获得裁剪结果,我假设您需要使用 Fragment#startActivityForResult 启动库活动。

    点击适配器项时调用Fragment#startActivityForResult,我可以想到两种方法:

    1. 将片段的实例传递给适配器类,并在单击项目时从片段开始活动。

    2. 定义一个 on 监听器并将其从片段传递给适配器,以便处理适配器的点击事件

    也许问题和下面的评论会有所帮助: https://github.com/ArthurHub/Android-Image-Cropper/issues/762#issuecomment-648859151


    (如果你能澄清你知道或做过什么、你尝试过什么以及你不知道什么,这可能会有所帮助,以便其他人更容易理解你的情况和理解水平。例如,您可以给我们一些您已经尝试过的其他代码或逻辑,让其他人更清楚地了解您的情况。)

    【讨论】:

    • 在片段中使用库不是我想要的,在适配器类中使用它是
    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2017-04-28
    • 2021-04-10
    相关资源
    最近更新 更多