How to Display Navigation Drawer in all activities?

后端 未结 8 1265
刺人心
刺人心 2020-11-27 13:39

I have a Navigation Drawer which should appear in all my activities.

I saw many questions similar to this & found a solution like Extending the Main

8条回答
  •  生来不讨喜
    2020-11-27 14:23

    I made a BaseActivity activity which extends SherlockActivity (or ActionBarActivity if is your case)

    public class BaseActivity extends SherlockActivity
    

    Then, make all your activities extends BaseActivity, like:

    public class GlossaryActivity extends BaseActivity
    

    Later, you must replace the activity layout with the one that correspond to your activity, I made a method in BaseActivity like that:

    protected void replaceContentLayout(int sourceId, int destinationId) {
        View contentLayout = findViewById(destinationId);
    
        ViewGroup parent = (ViewGroup) contentLayout.getParent();
        int index = parent.indexOfChild(contentLayout);
    
        parent.removeView(contentLayout);
        contentLayout = getLayoutInflater().inflate(sourceId, parent, false);
        parent.addView(contentLayout, index);
    }
    

    I called this method on the onCreate method in each activity:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.replaceContentLayout(R.layout.activity_glossary, super.CONTENT_LAYOUT_ID);
    
    }
    

    super.CONTENT_LAYOUT_ID is the FrameLayout of the BaseActivity, and other param is the layout you want replace with

提交回复
热议问题