我正在尝试实现导航抽屉,但findViewById(R.id.drawer_layout)
总是返回null
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.customToolbar);
toolbar.setTitle("Title");
setSupportActionBar(toolbar);
createDrawerNavigation();
}
private void createDrawerNavigation() {
drawerLayout = findViewById(R.id.drawer_layout);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if(menuItem.getItemId() == android.R.id.home) {
Log.v("","DDDDDDDDDDDD");
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
else
return super.onOptionsItemSelected(menuItem);
}
app_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/drawer_menu"
app:headerLayout="@layout/drawer_header"
android:fitsSystemWindows="true" />
</android.support.v4.widget.DrawerLayout>
当我点击菜单按钮应用程序崩溃与此错误 -
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference```
您已将您的布局文件命名为app_drawer.xml
,但在您的Activity中,您正在调用setContentView(R.layout.activity_main).
将布局文件名更改为activity_main.xml
,或将java代码中的行更改为setContentView(R.layout.app_drawer)
;