Reputation: 51
I have created a navigation drawer activity and I want to remove the toolbar of the activity and use the custom toolbar in different fragments, now I can't find any way to open and close the navigation drawer from inside the fragment. Like in main navigation activity the drawer can be open and closed on the click of the hamburger menu, but how can I open the drawer from the attached fragment to it.
Upvotes: 1
Views: 578
Reputation: 1145
Use custom listener:
class Frag extends Fragment{
NavigationOpenListener listener;
public interface NavigationOpenListener{
public void OnDrawerOpen();
}
public void openDrawer(){ // Call this method when you want to open drawer from your Fragment
if(listener!=null)
listener.OnDrawerOpen();
}
public void setOnDrawerOpenListener(NavigationOpenListener onDrawerOpenListener){
this.listener=onDrawerOpenListener;
}
}
And listen on your Activity
:
Frag frag1=new Frag();
frag1.setOnDrawerOpenListener(new Frag.NavigationOpenListener() {
@Override
public void OnDrawerOpen() {
yourDrawerLayout.openDrawer(GravityCompat.START);
}
});
Upvotes: 1
Reputation: 306
First of all create static instance of navigation drawer activity and then call public method of change fragment from your fragment like following
public class MainActivity extends AppCompatActivity
{
static MainActivity instance;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
instance=this;
}
public static MainActivity getInstance()
{
return instance;
}
public void changeFragment(Fragment targetFragment)
{
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_main_container, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
}
From Fragment call method like following
MainActivity mainActivity=MainActivity.getInstance();
mainActivity.changeFragment(new FragmentHome());
Upvotes: 0