Search code examples
javaandroidandroid-fragmentsandroid-dialogfragmentbottom-sheet

Start BottomSheetFragment for result


I want to get results from BottomSheetFragment. I tried to do it through getActivity().setResult(Activity.RESULT_OK, null); inside

    @Override
public void onDismiss(DialogInterface dialog) {
    getActivity().setResult(Activity.RESULT_OK, null);
    super.onDismiss(dialog);
}

but activity's method onActivityResult not called. What am I doing wrong?

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(this, requestCode, Toast.LENGTH_SHORT).show();
    super.onActivityResult(requestCode, resultCode, data);
}

Dialog start method

BottomSheetDialogFragment bottomSheetFragment = new BottomSheetDialogFragment();
            Bundle bundle = new Bundle();
            bottomSheetFragment.setArguments(bundle);
            bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());

Solution

  • onActivityResult() is used for getting a result from another Activity.

    More on this: https://developer.android.com/training/basics/intents/result

    If you want to send some data from Fragment to Activity, you can do it either by defining an interface or call a method in the Activity by casting it to the specific Activity.

    class MainActivity extends AppCompatActivity {
    
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
      YourBottomSheetDialogFragment bottomSheetFragment = new YourBottomSheetDialogFragment();
      Bundle bundle = new Bundle();
      bottomSheetFragment.setArguments(bundle);
      bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
     }
    
     public void setResultFromFragment(String data) {
      ...
     }
    }
    
    /**
    * Calling Activity's method from Fragment
    */
    class YourBottomSheetDialogFragment extends BottomSheetDialogFragment {
    
     @Override
     public void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ((MainActivity) getActivity()).setResultFromFragment("");
     }
    }