Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from Bottom Sheet Dialog Fragment

I'm starting bottomSheetDialogFragment from a fragment A. I want to select the date from that bottomSheetDialogFragment then set it in the fragment A.

The select date is already done, I just want to get it in the fragment A to set it in some fields.

How can I get the value? Any suggestions how to do it?

like image 937
Abdulrahman Avatar asked Apr 12 '18 10:04

Abdulrahman


People also ask

How do I return data from BottomSheetDialogFragment?

You can just call getActivity() and cast it to whatever your Activity's class name is: mAdapter = new similarContactAdapter(contItems, getActivity(). getApplicationContext(), new similarContactAdapter.

How pass data from fragment to bottom sheet in Android?

You can add BottomSheetFragment in your nav_graph and pass data as an argument of action . And finally, get the result as mentioned in the document.


2 Answers

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.

like image 148
AbhayBohra Avatar answered Oct 19 '22 22:10

AbhayBohra


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.

like image 29
hglf Avatar answered Oct 19 '22 22:10

hglf