Get value from Bottom Sheet Dialog Fragment

Android navigation architecture component

eg:

Suppose you open Fragment B from Fragment A using navController.

and you want some data from fragment B to Fragment A.

class B :BottomSheetDialogFragment() {

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.your_layout, container, false)

        root.sampleButton.setOnClickListener {
            val navController = findNavController()
            navController.previousBackStackEntry?.savedStateHandle?.set("your_key", "your_value")
            dismiss()

        }
}

and in your Fragment A:

findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<String>("your_key")
                ?.observe(viewLifecycleOwner) {
    
                    if (it == "your_value") {
                        //your code
    
                    }
    
                }

override the constructor of a fragment is a bad practice as the document said:

Every fragment must have an * empty constructor, so it can be instantiated when restoring its * activity's state.

if you using another constructor that passing a callback as the param, when the fragment is resotored by the framework, your app crash

the recommend way is using viewModel and livedata.


Create an interface class like this

public interface CustomInterface {

    public void callbackMethod(String date);
}

Implement this interface in your Activity or Fragment. and make an object of this Interface.

private CustomInterface callback;

Initialize it in onCreate or onCreateView

callback=this;

Now pass this callback in your BottomSheetDialogFragment constructor when you call it.

yourBottomSheetObject = new YourBottomSheet(callback);
yourBottomSheetObject.show(getSupportFragmentManager()," string");

Now in your BottomSheetFragment's constructor

private CustomInterface callback;

public SelectStartTimeSheet(CustomInterface callback){

this.callback=callback;

}

And at last use this callback object to set your date

callback.callbackMethod("your date");

and yout will recieve this date in your Fragment or Your Activity in callbackMethod function.