gpt4 book ai didi

java - Java 中的简短形式 toast

转载 作者:行者123 更新时间:2023-12-02 09:27:24 25 4
gpt4 key购买 nike

当我用 Kotlin 语言创建应用程序时,我创建了 Utils 类,并在其中创建了一个在整个项目中显示 Toast 的方法。我的代码如下所示:

fun Context.showToastShort(text: String, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, text, duration).show()
}

fun Context.showToastLong(text: String, duration: Int = Toast.LENGTH_LONG) {
Toast.makeText(this, text, duration).show()
}

现在我想在 Java 项目中执行此操作。我如何在Java中实现这样的方法?我不明白如何使用上下文扩展我的方法

最佳答案

如果你想这样做,你可以使用这样的类。

public class MyUtils {

private Context mContext;

public MyUtils(Context context) {
mContext = context;
}

public void displayToast(String message, int lenght){
if (lenght == 0){
Toast.makeText(mContext,message,Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
}

在上下文中创建类的实例并像这样在任何地方调用。

MyUtils myUtils = new MyUtils(getContext());
myUtils.displayToast("Hello world",0);

关于java - Java 中的简短形式 toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com