can we call startActivityForResult from adapter?How to get the response?

后端 未结 5 1683
说谎
说谎 2020-12-14 06:18

is it possible to have method startActivtyForResult within an adapter?Then how to get the response? Where to execute the call back function?

5条回答
  •  隐瞒了意图╮
    2020-12-14 07:10

    Yes.You can call startactivityforresult() from adapter.

    There are two case- 1.Calling adapter from activity and need onActivityResult in activity. 2.Calling adapter from Fragment and need onActivityResult in fragment.

    Case 1:Get OnActivityResult in Activity then pass the reference of activity to adapter constructor

    public MyAdapter(Activity pActivity, List pList) {
            mList = pList;
            mActivity = pActivity;       
        }
    

    Now startActivityForResult

    Intent intent = new Intent(context, TargetActivity.class);
    mActivity.startActivityForResult(intent, REQUEST_FOR_ACTIVITY_CODE);
    

    Case 2: Get OnActivityResult in Fragment then pass the reference of fragment to adapter constructor

     public MyGamesAdapter(Fragment pContext, List pList,) {
            mList = pList;
            mMyFragment =pContext;
        }
    
     Intent intent = new Intent(context, TargetActivity.class);
        mMyFragment.startActivityForResult(intent, REQUEST_FOR_ACTIVITY_CODE);
    

    Now in activity or fragment override OnActivityResult and get result.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mAdapter.onActivityResult(requestCode, resultCode, data);
    }
    

提交回复
热议问题