我从我的容器活动访问了bottomnavigation视图,并将选定的侦听器项设置为底部导航视图。 以下代码在我的onCreateView片段中。
b2 = (BottomNavigationView) getActivity().findViewById(R.id.botttom_nav);
b2.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.songs:
selectedFragment=new SongsFragment();
break;
case R.id.albums:
selectedFragment=new AlbumFragment();
break;
case R.id.artists:
selectedFragment=new ArtistFragment();
Bundle bundle = new Bundle();
bundle.putStringArrayList("artists",songArtists);
selectedFragment.setArguments(bundle);
break;
case R.id.playlists:
selectedFragment=new PlaylistsFragment();
break;
}
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_main,selectedFragment).commit();
return true;
}
});
显示fragmentmanager的错误。
错误日志如下所示:
PID: 22518
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
at com.noob.audioplayer.SongsFragment$2.onNavigationItemSelected(SongsFragment.java:215)
at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:204)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at android.support.design.internal.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:115)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
答案 0 :(得分:0)
在您的代码getActivity()
中为空,因此您需要显示片段的活动的上下文。
在您的片段中声明一个变量
private YOUR_Activity myContext;
然后在片段中覆盖onAttach()
@Override
public void onAttach(Activity activity) {
myContext=(YOUR_Activity) activity;
super.onAttach(activity);
}
然后您这样叫supportFragmentManager
FragmentManager fragmentManager = myContext.getSupportFragmentManager();