简体   繁体   English

设置工具栏小部件标题时出现空指针异常

[英]Null pointer exception when setting title of toolbar widget

I'm trying to set a title for my toolbar widget, but after doing so the last line of my code becomes highlighted in yellow and I get a null pointer exception warning. 我正在尝试为工具栏小部件设置标题,但是这样做之后,我的代码的最后一行以黄色突出显示,并且出现空指针异常警告。 What can be done to solve this issue? 如何解决这个问题?

Method invocation 'getSupportActionBar().setTitle(Html.fromHtml("" + getResources().getString(R.string.hello_world) + ""));' 方法调用'getSupportActionBar()。setTitle(Html.fromHtml(“” + getResources()。getString(R.string.hello_world)+“”));' may produce 'java.lang.NullPointerException' 可能会产生'java.lang.NullPointerException'

   Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(mToolbar);
   getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hello_world) + "</font>"));

The null pointer exception is only going to be thrown if the action bar would not be set. 仅在不设置操作栏的情况下才会抛出空指针异常。 In your case it was merely a warning, there should be no error. 就您而言,这只是一个警告,应该没有错误。 However if you want to get rid of your warning try wrapping it with 'if' statement: 但是,如果您想摆脱警告,请尝试使用'if'语句将其包装:

if (getSupportActionBar() != null) {
    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hello_world) + "</font>"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM