java - Android - 在 Android 中设置自定义工具栏时出现 NullPointerException
问题描述
我正在尝试将自定义图像设置到我的标题栏中。
运行以下代码将返回以下内容:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.me.project/com.me.project.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setTitle(int)' on a null object reference
toolbar
一片空白。为什么?R.id.app_toolbar
在这里不为空。
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar toolbar = findViewById(R.id.app_toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setLogo(R.drawable.app_icon);
setSupportActionBar(toolbar);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, new HomeScreenFragment());
fragmentTransaction.commit();
}
活动主.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_activity"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="@+id/app_toolbar"
layout="@layout/app_toolbar"/>
<FrameLayout
android:id="@+id/container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
app_toolbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/app_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
>
</android.support.v7.widget.Toolbar>
我看了看这个,无法解决这个问题。
解决方案
你应该添加setContentView(R.layout.activity_main)
到onCreate()
推荐阅读
- php - FPDF - PHP - 中心单元格上的不同样式
- sql - SQL 查询 - 不使用嵌套子查询
- php - Angular 2 无法加载预检响应无效(重定向)
- sql - MS Access - 更新单元格的值
- python - 如何从 django 中的数组中读取输入
- lambda - 使用 terraform 的自定义 API 网关授权器
- c++ - 如何使文本在饼图的每个切片中居中?
- javascript - selectize.js 在动态创建的选择元素上
- windows - 使用 pywin32 库中的 win32evtlog 写入 Windows 事件日志
- tfs-power-tools - TFPT 跨工作区取消搁置/迁移