I'm implementing a navigation drawer activity in which I have a fragment(consisting of recycler view) in the navigation drawer to dynamically add items to navigation drawer.
I've successfully implemented this concept but am facing a small issue that the navigation drawer does not close when I click on any item in fragment. This is because I'm not able to access DrawerLayout from fragment.
So how do I pass a click listener from my fragment to the activity to close the drawer layout.
Thank you.
Here is a simple solution to do that. Create an interface
public interface ClickInterface {
public void buttonClicked();
}
Then in your activity , implement this interface
public class MainActivity extends Activity implements ClickInterface{
@override
public void buttonClicked() {
//do your code here
}
onCreate() {
fragment.setInterface(this);
}
Now call this method buttonclicked from fragment class
public class ChildFragment extends Fragment {
ClickInterface interface;
//call this method from activity when activity loads the fragment inside it
public void setInterface(ClickInterface interface) {
this.interface = interface;
}
public void onClick(View v) {
interface.buttonClicked();
}
}