gpt4 book ai didi

java - Drawer_layout 的 findViewById 始终返回 null

转载 作者:行者123 更新时间:2023-12-02 10:15:19 24 4
gpt4 key购买 nike

我正在尝试实现抽屉导航,但 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);

关于java - Drawer_layout 的 findViewById 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54725945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com