[英]Toast method for displaying messages
I created a method for toast the problem is in some cases I want to display a toast message with an integer and sometimes I want to display toast message without the integer.我创建了一个 toast 方法,问题是在某些情况下我想显示一个带有整数的 toast 消息,有时我想显示没有整数的 toast 消息。 I know this could be made possible by creating two separate functions but is it possible with one method itself.我知道这可以通过创建两个单独的函数来实现,但是否可以使用一种方法本身。
public void maketoast(String string, Integer inte){
Toast.makeText(this, string+inte, Toast.LENGTH_SHORT).show();
}
The following are the cases of the method call :以下是方法调用的情况:
maketoast("Greater than ",2);
maketoast("Greater ",null);
Output: In first call, I need the output as "Greater than 2" In the second call I need the output as "Greater" but currently I am getting "Greater null"输出:在第一次调用中,我需要输出为“大于 2”在第二次调用中我需要输出为“更大”但目前我得到“更大的空值”
Java has a ternary operator . Java 有一个三元运算符。 Using it will help to abbreviate your code:使用它有助于简化您的代码:
public void maketoast(String string, Integer inte){
Toast.makeText(this, inte != null ? string+inte : string, Toast.LENGTH_SHORT).show();
}
Adding null to a string converts null to "null".向字符串添加 null 会将 null 转换为“null”。 I recommend this我推荐这个
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.