BaseActivity for Navigation

前端 未结 6 1731
猫巷女王i
猫巷女王i 2020-12-24 09:21

I\'m building a base activity for navigation and want something flexible so the Activity dictates to the Base Activity which layout to inflate.

I have the following<

6条回答
  •  攒了一身酷
    2020-12-24 10:16

    You can refer to my following code, pay attention to addContentView in my base activity (here I name it NavigationDrawerActivity)

    Base activity:

    public class NavigationDrawerActivity extends AppCompatActivity {
        private DrawerLayout mDrawerLayout;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_navigation_drawer);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
            mDrawerLayout.setDrawerListener(toggle);
            toggle.syncState();
        }
        /**
         * called in extending activities instead of setContentView...
         *
         * @param layoutId The content Layout Id of extending activities
         */
        public void addContentView(int layoutId) {
            LayoutInflater inflater = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View contentView = inflater.inflate(layoutId, null, false);
            mDrawerLayout.addView(contentView, 0);
        } 
    }
    

    Then in other activities, for example, MainActivity:

    public class MainActivity extends NavigationDrawerActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.addContentView(R.layout.activity_main);
        }
    }
    

    Hope this helps!

提交回复
热议问题