【问题标题】:Toast method for displaying messagesToast 显示消息的方法
【发布时间】:2019-11-25 20:48:24
【问题描述】:

我创建了一个 toast 方法,问题是在某些情况下我想显示一个带有整数的 toast 消息,有时我想显示没有整数的 toast 消息。我知道这可以通过创建两个单独的函数来实现,但可以通过一种方法本身来实现。

public void maketoast(String string, Integer inte){
    Toast.makeText(this, string+inte, Toast.LENGTH_SHORT).show();
}

以下是方法调用的情况:

maketoast("Greater than ",2);
maketoast("Greater ",null);

输出: 在第一次通话中,我需要输出为“大于 2” 在第二次调用中,我需要输出为“Greater”,但目前我得到的是“Greater null”

【问题讨论】:

    标签: java android android-toast


    【解决方案1】:

    Java 有一个ternary operator。使用它将有助于缩写您的代码:

    public void maketoast(String string, Integer inte){
        Toast.makeText(this, inte != null ? string+inte : string, Toast.LENGTH_SHORT).show();
    }
    

    【讨论】:

      【解决方案2】:

      将 null 添加到字符串会将 null 转换为“null”。我推荐这个

      public void maketoast(String string, Integer inte){
          if(inte == null) 
            Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
          else
            Toast.makeText(this, string+inte, Toast.LENGTH_SHORT).show();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-12
        • 2011-12-09
        • 2014-07-04
        • 1970-01-01
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多