点击侧边导航菜单项无法启动Activity并抛出空指针异常
简易侧边导航跳转崩溃问题排查
实际开发场景
按照自定义实现方式做简易导航菜单,预期点击菜单项时可以跳转到对应新Activity。目前运行状态为:从主Activity跳转到其他Activity可以正常运行无报错,但在其他页面点击侧边导航菜单项时应用会直接崩溃。已经确认所有Activity都在Manifest清单文件中完成注册,找不到问题根源,是Android开发初学者求助。
现有实现代码片段
MainActivity 代码
public class MainActivity extends AppCompatActivity{ DrawerLayout drawerLayout; RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); drawerLayout = findViewById(R.id.drawer_layout); recyclerView = findViewById(R.id.rv2); recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false)); TextView next = (TextView) findViewById(R.id.cards); next.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), Cards.class); startActivityForResult(myIntent, 0); } }); ImageView hamburger = (ImageView) findViewById(R.id.menu_ham); hamburger.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { drawerLayout.openDrawer(Gravity.START); } }); } }
Cards 页面代码
public class Cards extends AppCompatActivity { DrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cards); drawerLayout = findViewById(R.id.drawer_layout); ImageView hamburger = (ImageView) findViewById(R.id.menu_ham); hamburger.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { drawerLayout.openDrawer(Gravity.START); } }); TextView home = (TextView) findViewById(R.id.home); home.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), MainActivity.class); startActivityForResult(myIntent, 0); } }); } }
布局文件代码
activity_cards.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/drawer_layout" tools:context=".Cards"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/main_toolbar" /> </LinearLayout> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="50dp" android:background="@color/white" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cards" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.drawerlayout.widget.DrawerLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/drawer_layout" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/main_toolbar" /> <androidx.recyclerview.widget.RecyclerView android:padding="15dp" android:id="@+id/rv2" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> <RelativeLayout android:layout_width="300dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="@color/white"> <include layout="@layout/main_nav_drawer" /> </RelativeLayout> </androidx.drawerlayout.widget.DrawerLayout>
- 通用侧边导航布局
main_nav_drawer.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <ImageView android:layout_width="80px" android:layout_height="80px" android:layout_marginLeft="15dp"/> <TextView android:id="@+id/home" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="27dp" android:layout_weight="1" android:padding="12dp" android:text="Home" android:textSize="18dp" android:textStyle="bold" android:textColor="#000"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <ImageView android:layout_width="80px" android:layout_height="80px" android:layout_marginLeft="15dp"/> <TextView android:id="@+id/cards" android:textColor="#000" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Cards" android:padding="12dp" android:textStyle="bold" android:textSize="18dp" android:layout_marginLeft="27dp"/> </LinearLayout> </LinearLayout>
- 通用顶栏布局
main_toolbar.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="12dp" android:gravity="center_horizontal"> <ImageView android:id="@+id/menu_ham" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_baseline_menu_24"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="android coding" android:textSize="20sp" android:textStyle="bold" android:textAlignment="center" android:textColor="#636363" android:gravity="center_horizontal" /> </LinearLayout>
崩溃日志
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.myapplication0000, PID: 24658 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication0000/com.example.myapplication0000.Cards}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.myapplication0000.Cards.onCreate(Cards.java:31) at android.app.Activity.performCreate(Activity.java:8000) at android.app.Activity.performCreate(Activity.java:7984) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
问题根因与修复方案
报错的直接原因和Manifest注册无关,是布局缺失导致的空指针:
home、cards这两个菜单项的TextView,是定义在main_nav_drawer.xml这个侧边导航布局里的,不是全局通用的id。- 主页面
MainActivity对应的activity_main.xml中,在DrawerLayout容器里正确放置了侧边导航块(包含main_nav_drawer的RelativeLayout),所以在MainActivity里通过findViewById可以正常找到这两个菜单项View,跳转逻辑运行正常。 - 但
Cards页面对应的activity_cards.xml中,DrawerLayout容器下只放了两个子View:一个是带顶栏的主内容区,另一个是展示“Cards”文本的内容块,完全没有引入侧边导航布局。当在Cards的onCreate中调用findViewById(R.id.home)时,系统在当前布局树里根本找不到这个id对应的View,返回了null,后续调用setOnClickListener()就触发了空指针崩溃。
具体修复步骤
- 补齐
activity_cards.xml的侧边导航结构
在DrawerLayout的现有子项末尾,追加和MainActivity中结构一致的侧边栏布局块,让当前页面的布局树里包含home、cards对应的View:
补齐后<RelativeLayout android:layout_width="300dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="@color/white"> <include layout="@layout/main_nav_drawer" /> </RelativeLayout>findViewById(R.id.home)就能正常拿到View实例,不会再返回null。 - 优化跳转逻辑,避免Activity栈堆积
目前代码里用startActivityForResult但没有处理任何回调结果,完全可以替换为普通的startActivity,同时给跳转Intent加上FLAG_ACTIVITY_REORDER_TO_FRONT标记,避免反复点击菜单导致栈里重复创建多个相同的Activity实例。比如从Cards页点击Home返回Main时,系统会把已存在的Main实例挪到栈顶,而不是新建一个Main叠在栈上,减少内存占用。 - 抽取公共逻辑降低出错概率
现在每个带侧边导航的Activity,都要重复写打开抽屉、绑定菜单点击事件的代码,漏写任何一个布局块都会触发空指针。后续可以把抽屉初始化、菜单点击事件绑定的逻辑抽取成公共工具类,所有页面复用这套逻辑,不用每个Activity重复写重复代码,降低新手开发的出错概率。
内容的提问来源于stack exchange,提问作者Fathpath
相关产品推荐
相关产品推荐

