can we call startActivityForResult from adapter?

后端 未结 4 703
无人共我
无人共我 2021-02-03 19:10

is it possible to have method onActivityResume within adapter & call startActivityForResult?

相关标签:
4条回答
  • 2021-02-03 19:35

    Not necessarily pass to pass context in adapter's constructor. You can get context from parent ViewGroup. Sample for RecyclerView adapter:

     Context mContext;
     @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            mContext = parent.getContext();
            ...
        }
    

    Sample for ListView BaseAdapter

     Context mContext;
     @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            mContext = parent.getContext();
            ...
    }
    

    And use it wherever you want

    ((Activity) mContext).startActivityForResult(intent, REQUEST_FOR_ACTIVITY_CODE);
    
    0 讨论(0)
  • 2021-02-03 19:54

    Yes. Just pass the context of the activity to the adapter in the adapter's constructor (here stored as mContext). In getView, just call

    ((Activity) mContext).startActivityForResult(intent,REQUEST_FOR_ACTIVITY_CODE);
    
    0 讨论(0)
  • //First Do
    public Activity context;
    public int REQUEST_CODE = 111;
    
    public Adapter(Activity context, Data data) {
        this.context = context;
    }
    
    ///Second Do
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, NextActivity.class);
                context.startActivityForResult(intent, REQUEST_CODE);
            }
        });
    }
    

    If you follow this code then you don't need to write it - ((Activity) context) - every time, before - .startActivityForResult(intent, REQUEST_CODE); - when you use startActivityForResult in Adapter.

    0 讨论(0)
  • 2021-02-03 19:59

    Offcource...

    ((Activity) context).startActivityForResult(intent, 911);
    

    Caution !!

    Only pass MyActivity.this from activity to adapter as context.

    Only pass getActivity(); from fragment to adapter as context.

    0 讨论(0)
提交回复
热议问题