1.布局
外层是DrawerLayout
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/dl"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/ll"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v7.widget.Toolbar>
<FrameLayout
android:id="@+id/fg"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/nv"
android:layout_gravity="left"
app:headerLayout="@layout/activity_header"
app:menu="@menu/nv"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
2.主要中
@Override
protected void initView() {
mToolbar.setTitle("首页");
manager = getSupportFragmentManager();
setSupportActionBar(mToolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDl, mToolbar, R.string.about, R.string.about);
mDl.addDrawerListener(toggle);
toggle.syncState();
initFragment();
addFragment();
}
private void addFragment() {
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fg, list.get(0));
transaction.commit();
}
//自己创建fragmt
private void initFragment() {
list = new ArrayList<>();
list.add(new HomeFragment());
list.add(new CollectionFragment());
list.add(new SettingFragment());
list.add(new AboutFragment());
}
@Override
protected void initListener() {
mNv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.wan:
switchFragment(HOME);
break;
case R.id.collection:
switchFragment(COLLECTION);
break;
case R.id.setting:
switchFragment(SETTING);
break;
case R.id.about:
switchFragment(ABOUT);
break;
}
mDl.closeDrawer(Gravity.LEFT);
return false;
}
});
}
int HOME = 0;
int COLLECTION = 1;
int SETTING = 2;
int ABOUT = 3;
int LASTPOSITION = 0;
private void switchFragment(int position) {
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = list.get(position);
if (!fragment.isAdded()) {
transaction.add(R.id.fg, fragment);
}
Fragment lastfragment = list.get(LASTPOSITION);
transaction.hide(lastfragment);
transaction.show(fragment);
transaction.commit();
LASTPOSITION = position;
}
网友评论