显示消息的吐司方法

时间:2019-11-25 20:48:24

标签: java android android-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”

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

在字符串中添加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();
}