【问题标题】:Can getSupportActionBar be null right after setSupportActionBar?在 setSupportActionBar 之后 getSupportActionBar 可以为空吗?
【发布时间】:2015-08-04 09:45:47
【问题描述】:

我是否应该对 getSupportActionBar() 方法进行空检查,即使在该方法的早期我已经使用 getSupportActionBar() 设置了支持操作栏?

onCreate()我有三行

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getIntent().getStringExtra(TITLE_KEY));

Android Studio 然后给我警告

"Method invocation may produce java.lang.NullPointerException"

假设 findViewById 方法确实返回了一个有效的 ToolBar 对象,我是否仍需要对 getSupportActionBar() 方法进行空值检查,或者忽略警告是否安全?

【问题讨论】:

  • 警告不是错误。而且您所说的警告说“它可能会产生”,不要说“它必须产生”。
  • @DhawalSodhaParmar 如果它是“它必须生产”那会是什么???总是返回 null 的 getter 方法是 useless

标签: android android-studio android-toolbar


【解决方案1】:

这可能会产生 NullPointer 异常。

您已经创建了一个新的 Toolbar 对象,您可以使用toolbar.setTitle(getIntent().getStringExtra(TITLE_KEY)); 来设置标题。您需要在致电 setSupportActionBar(toolbar); 之前执行此操作

不需要调用getSupportActionBar(),因为已经设置的actionbar就是工具栏。因此,您可以直接使用该对象来编辑您的工具栏。这比 getSupportActionBar(); 快

【讨论】:

  • 问题是相关的,有些事情不能通过ToolBar完成,例如setDisplayHomeAsUpEnabled
  • @Mood 是的,但是对于提问者想做的事情工具栏没问题
  • 对不起@tim687 我很快就解决了这个问题。
  • 我看过这个。事实证明,在 setSupportActionBar() 之后执行 toolbar.setTitle() 不起作用。我发现这篇文章stackoverflow.com/questions/26486730/… 也谈到了这一点。与他的示例不同,但是如果我在调用 setSupportActionBar() 之前执行了 toolbar.setTitle(),我确实为我工作
  • 感谢您的回答。它确实使用 setTitle() 帮助了这个特定案例,但正如 Mood 指出的那样,我更多地询问如何处理 getSupportActioBar 方法,我觉得 NileshJarad 的答案更符合我的要求。但是,您的回答非常有用。
【解决方案2】:

我的建议是:- 不要检查 null 因为警告不是错误

您所说的警告说“它可能会产生”。它没有说“将必须产生”。

但如果你想加倍确定你可以检查 null

【讨论】:

    【解决方案3】:

    为避免出现此警告,您可以随时检查 ActionBar 对象是否为空。

    ActionBar mActionBar = getSupportActionBar();
    
        if (mActionBar != null) {
            mActionBar.setTitle(getIntent().getStringExtra(TITLE_KEY));
        }
    

    【讨论】:

      【解决方案4】:

      不,您不应该对此项进行空检查。因为如果假设失败(例如,如果 findViewById(R.id.toolbar) 开始返回 null,因为您在项目的另一个文件中引入了错误),您确实希望抛出 NullPointerException,因此您很容易找到测试时的错误。

      换句话说:在我看来,最好的方法是fail fast

      我的代码看起来像这样,带有使警告静音的注释:

      //noinspection ConstantConditions: Action bar should always be present. If not, we prefer a NullPointerException here.
      getSupportActionBar().setHomeButtonEnabled(true);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-28
        • 1970-01-01
        • 2013-02-21
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多