利用fragmentationx 管理fragment
效果图:
第一,导入依赖
implementation 'me.yokeyword:fragmentationx:1.0.2'
第二,编写mian.xml
注意:
NavigationView中的标签
app:menu="@menu/menu_list"
android:layout_gravity="start"
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/draw"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/cons"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:menu="@menu/menu_list"
android:layout_gravity="start" />
</androidx.drawerlayout.widget.DrawerLayout>
第三,编写menu_list.xml
–该文件要放在menu文件夹中
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/me_weather"
android:title="WeatherDemo" />
<item
android:id="@+id/me_pm25"
android:title="PM2.5指数" />
<item
android:id="@+id/me_weizhang"
android:title="违章车辆的占比统计" />
<item
android:id="@+id/me_shi"
android:title="实时数据" />
<item
android:id="@+id/me_bar"
android:title="年龄群体车辆违章" />
<item
android:id="@+id/me_pai"
android:title="排名前十位" />
</menu>
第四,MainActivity中继承SupportActivity
1,NavigationView调用setNavigationItemSelectedListener 进行管理Fragment
2,调用的Fragment也要继承 SupportFragment
public class MainActivity extends SupportActivity {
private FrameLayout cons;
private DrawerLayout draw;
private NavigationView nav;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initfid();
loadRootFragment(R.id.cons,new WelcomeFragment());
nav.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.me_weather:
startWithPop(new WeatherFragment());
draw.closeDrawers();
break;
case R.id.me_pm25:
startWithPop(new PM25Fragment());
draw.closeDrawers();
break;
case R.id.me_weizhang:
startWithPop(new NoAndFragment());
draw.closeDrawers();
break;
case R.id.me_shi:
startWithPop(new ShiFragment());
draw.closeDrawers();
break;
case R.id.me_bar:
startWithPop(new BarFragment());
draw.closeDrawers();
break;
case R.id.me_pai:
startWithPop(new PaiMFragment());
draw.closeDrawers();
break;
}
return true;
}
});
}
private void initfid() {
cons = findViewById(R.id.cons);
draw = findViewById(R.id.draw);
nav = findViewById(R.id.nav);
}
}