简体   繁体   English

如何处理onActivityResult覆盖方法的接口

[英]How to handle interface for onActivityResult Override Method

I want to use onActivityResult method in Adapter but after searching on Stack Overflow I found I have to make interface for onActivityResult but I donot know how to make this and handle onActivityResult Methode to work as per my need. 我想在Adapter中使用onActivityResult方法,但在搜索Stack Overflow之后,我发现我必须为onActivityResult创建接口,但我不知道如何制作它并根据我的需要处理onActivityResult Methode。

Here is my Adapter Class. 这是我的适配器类。

    public class PosterAdapter extends RecyclerView.Adapter<PosterAdapter.PosterViewHolder> {


    private static final String TAG = "resPoster";
    private ArrayList<Poster> posterArrayList;
    private Context context;



    public PosterAdapter(ArrayList<Poster> posterArrayList, Context context) {
        this.posterArrayList = posterArrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public PosterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.sending_image_layout, viewGroup, false);

        return new PosterViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull PosterViewHolder posterViewHolder, int i) {

        posterViewHolder.imageViewDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(true);

                Bitmap bitmap = Bitmap.createBitmap(posterViewHolder.relativeLayoutImage.getDrawingCache());
                posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(false);


                FileOutputStream outStream = null;
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + "/providers");
                dir.mkdirs();
                String fileName = String.format("%d.jpg", System.currentTimeMillis());
                Log.d(TAG,"filename: " +  fileName);
                File outFile = new File(dir, fileName);
                Log.d(TAG,"outFile: " +  outFile);
                try {
                    outStream = new FileOutputStream(outFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        posterViewHolder.imageViewEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
//                startActivityForResult(i, 0);
                ((Activity) context).startActivityForResult(Intent.createChooser(i, "CHOOSING INTENT"), 0);
            }
        });



    }





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

    public class PosterViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout relativeLayoutImage;
        ImageView imageViewBg, imageViewEdit, imageViewDownload, imageViewShare;
        CircleImageView imageViewProfie;

        public PosterViewHolder(@NonNull View posterView) {
            super(posterView);

            relativeLayoutImage = posterView.findViewById(R.id.image_relative);
            imageViewBg = posterView.findViewById(R.id.image_bg);
            imageViewProfie = posterView.findViewById(R.id.image_profile_moving);
            imageViewEdit = posterView.findViewById(R.id.edit_image);
            imageViewDownload = posterView.findViewById(R.id.download_image);
            imageViewShare = posterView.findViewById(R.id.share_image);

        }
    }

}

and I want to use this class 我想用这个班

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (requestCode == 0) {
            final Uri selectedUri = data.getData();
            if (selectedUri != null) {
                startCrop(selectedUri);
            } else {
                Toast.makeText(context, "Cannot retrieve selected Image", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == UCrop.REQUEST_CROP) {
            handleCropResult(data);
        }
    }
    if (resultCode == UCrop.RESULT_ERROR) {
        handleCropError(data);
    }
}

Please Help me handle this method in interface. 请帮我在界面中处理这个方法。 Thank you. 谢谢。

**UPDATE: ** **更新:**

Here is my activity code to understand more my question. 这是我的活动代码,以了解更多我的问题。

     RequestQueue requestQueue;
    private ArrayList<Poster> posterArrayList = new ArrayList<>();
    private RecyclerView recyclerView;
    private PosterAdapter posterAdapter;

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

        requestQueue = Volley.newRequestQueue(this);

        recyclerView = findViewById(R.id.recycler_poster);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));


        getAllPoster();
    }

    private void getAllPoster() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("poster_id", "1");

        Log.d(TAG + "pp", String.valueOf(params));




        String Url = Constants.Base_URL + "poster/";

        JsonObjectRequest request = new JsonObjectRequest(Url,  new JSONObject(params),
                response -> {
                    Log.d("responsePending", String.valueOf(response));

                    try {
                        String statusResponseObject = response.getString("status");
                        String msgObject = response.getString("msg");

                        if (statusResponseObject.equals("200")){

                            JSONArray jsonArray = response.getJSONArray("response");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject pendingFragResponse = jsonArray.getJSONObject(i);

                                String posterObject = pendingFragResponse.getString("poster");
                                String positionObject = pendingFragResponse.getString("position");
                                String sizeObject = pendingFragResponse.getString("size");
                                String txt_positionObject = pendingFragResponse.getString("txt_position");
                                String titleObject = pendingFragResponse.getString("title");
                                String descriptionObject = pendingFragResponse.getString("description");


                                //

                                posterArrayList.add(new Poster(posterObject, positionObject,
                                        sizeObject, txt_positionObject,
                                        titleObject, descriptionObject));
                                posterAdapter = new PosterAdapter( posterArrayList, SendingImageActivity.this);
                                recyclerView.setAdapter(posterAdapter);
//                                wp10ProgressBar.hideProgressBar();
//                                wp10ProgressBar.setVisibility(View.GONE);

                            }
                            posterAdapter.notifyDataSetChanged();
//                            wp10ProgressBar.hideProgressBar();
                        }else {
//                            wp10ProgressBar.hideProgressBar();
//                            wp10ProgressBar.setVisibility(View.GONE);
                            Toast.makeText(SendingImageActivity.this, msgObject, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                    }



                }, error -> {
            error.printStackTrace();
            Log.d(TAG + "error", String.valueOf(error.getMessage()));
            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();

        });

        requestQueue.add(request);
    }




}


                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                    }



                }, error -> {
            error.printStackTrace();
            Log.d(TAG + "error", String.valueOf(error.getMessage()));
            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();

        });

        requestQueue.add(request);
    }




}

Rather than using Interface pattern just create public method inside your adapter and call that method when your onActivityResult hits in Activity . 而不是使用Interface模式只需在适配器内创建公共方法,并在onActivityResultActivity命中时调用该方法。

(This answer is just a workaround for your scenario. Ideally you should not pass your activity Context to your adapter, rather than use Interface pattern and receive callback inside your activity whenever any action took place (like clicking on edit button) inside your activity and pass relevant data while trigger callback from your adapter.) (这个答案只是针对您的场景的一种解决方法。理想情况下,您不应该将活动Context传递给适配器,而不是在活动内部发生任何操作(例如单击编辑按钮)时使用Interface模式并在活动中接收回调。传递相关数据,同时触发适配器的回调。)

You can refer AllNoteActivity and NoteAdapter for reference here 您可以在此处参考AllNoteActivity和NoteAdapter以供参考

So what you need to do is put the current method onActivityResult() from PosterAdapter to the activity. 所以你需要做的是将当前方法onActivityResult()从PosterAdapter放到活动中。 Then make the methods startCrop(), handleCropResult() and handleCropError() public (I assume are in PosterAdapter). 然后使方法startCrop(),handleCropResult()和handleCropError()public(我假设在PosterAdapter中)。

In the onActivityResult() change the call of startCrop() to posterAdapter.startCrop(). 在onActivityResult()中,将startCrop()的调用更改为posterAdapter.startCrop()。 Same for the other methods. 其他方法也一样。 And that should do it. 这应该做到这一点。

Create a method in adapter 在适配器中创建方法

In your adapter class 在您的适配器类中

    public void waterverYouWantMethod(){

}

And call that method from Activity when onActivityResult mehtod called. 当onActivityResult mehtod调用时,从Activity调用该方法。

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
   // call that method here
adapter.wateverYouWantMethod();


    }

    }

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

相关问题 无法覆盖 OnActivityResult 方法 - Can't override OnActivityResult method 如何检查startActivityForResult中按下了哪个按钮,并覆盖onActivityResult方法? - How to check which button was pressed in startActivityForResult, override onActivityResult method? 如何覆盖嵌套片段上的onactivityresult方法? - How I can override onactivityresult method on nested fragment? 如何处理onActivityResult? - How to handle onActivityResult? 如何使用Mortar处理onActivityResult() - How to handle onActivityResult() with Mortar Facebook SDK-如何正确覆盖onActivityResult()? - Facebook SDK - how to override onActivityResult() correctly? 如何在 RecyclerView 适配器中启动 ActivityForResult 并覆盖 onActivityResult? - How to startActivityForResult in RecyclerView adapter and override onActivityResult? 出现错误:覆盖方法应该调用 super.onActivityResult - Getting error: override method should call super.onActivityResult 如何从Fragment到达onActivityResult()并进行处理? - How to reach onActivityResult() from Fragment and handle it? 如何在撰写导航中处理类似于 onActivityResult 的行为? - How to handle behavior similar to onActivityResult in compose navigation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM