我在编辑工具栏中的标题时遇到了一些麻烦。我想要标题,我一直在尝试一些不起作用的潜在解决方案。
当我运行以下代码时,我不断收到空指针异常。任何帮助,将不胜感激!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skill);
Intent in = getIntent();
String skill = in.getStringExtra("skill");
String detail = in.getStringExtra("detail");
String required = in.getStringExtra("required");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.titleskill);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbarTitle.setText(skill);
toolbar.setTitleMarginBottom(50);
// toolbar.setTitle(skill);
布局文件:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="128dp"
android:layout_width="match_parent"
android:background="?attr/colorPrimary"
android:minHeight="128dp"
app:popupTheme="@style/AppTheme.PopupOverlay"
android:gravity="bottom"
>
<TextView android:layout_height="match_parent"
android:layout_width="wrap_content"
android:fontFamily="sans-serif-light"
android:textColor="@color/text"
android:textSize="50dp"
android:id="@+id/titleskill"
android:maxLines="2"
>
</TextView>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
空指针异常:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at athena.sentineljs.com.athena.Skill.onCreate(Skill.java:49)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
答案 0 :(得分:1)
使用包含此标记的
标记将您的工具栏布局文件包含在您的activity_skill.xml中 <include layout="@layout/<your toolbar file name>"/>
示例:如果工具栏布局文件名是toolbar.xml,则include标记应如下所示,不带.xml扩展名
<include layout="@layout/toolbar"/>