Android: Navigation-Drawer on all activities

前端 未结 3 1246
醉酒成梦
醉酒成梦 2020-12-01 15:12

I want to add navigation drawer on all actvities of my Android project. This is the code of the MainActivity:

public class MainActivity extends Activity {

         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 16:07

    The easy way is that you should create fragments. If you are ready to for little hard thing then this is for you. It will let you have same navigation drawer in all activities.

    Create drawer_n_activity.xml

    
    
    
    
    
    
    
    
    
    

    Your DrawerActivity.class

    public class DrawerActivity extends Activity {
    
        public RelativeLayout fullLayout;
        public FrameLayout frameLayout;
    
        @Override
        public void setContentView(int layoutResID) {
    
            fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.drawer_n_activity, null);
            frameLayout = (FrameLayout) fullLayout.findViewById(R.id.drawer_frame);
    
            getLayoutInflater().inflate(layoutResID, frameLayout, true);
    
            super.setContentView(fullLayout);
    
            //Your drawer content...
    
        }
    }
    

    Now, to include same Navigation Drawer in all your activities and mind one more thing, all your activities must extend DrawerActivity

    public class MainActivity extends DrawerActivity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main); //layout for 1st activity
       }
    }
    
    public class SecondActivity extends DrawerActivity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second_activity); //layout for 2nd activity
       }
    }
    

提交回复
热议问题