我尝试在.getClass
和onNavigationItemSelected(MenuItem item)
中使用onPrepareOptionsMenu(Menu menu)
方法,但Logcat给了我一个错误PID: 6332
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
。
我的代码:
public boolean onPrepareOptionsMenu(Menu menu) {
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (activeFragment.equals(BookmarkFragment.class.getSimpleName())) {
menuSettings.setVisible(false);
toolbar.findViewById(R.id.edit_search).setVisibility(View.GONE);
toolbar.setTitle("Bookmark");
} else {
menuSettings.setVisible(true);
toolbar.findViewById(R.id.edit_search).setVisibility(View.VISIBLE);
toolbar.setTitle("");
}
return true;
}
和此:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_bookmark) {
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())) {
goToFragment(bookmarkFragment, false);
}
}
任何解决方案?
答案 0 :(得分:0)
这意味着
findFragmentById(R.id.fragment_container)
返回null。意味着没有这样的对象/片段。