Java中的短格式toast
当我用Kotlin语言创建应用程序时,我创建了Utils类,在那里我创建了一个方法,用于在整个项目中显示祝酒词。我的代码如下所示:Java中的短格式toast,java,android,android-studio,kotlin,Java,Android,Android Studio,Kotlin,当我用Kotlin语言创建应用程序时,我创建了Utils类,在那里我创建了一个方法,用于在整个项目中显示祝酒词。我的代码如下所示: fun Context.showToastShort(text: String, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, text, duration).show() } fun Context.showToastLong(text: String, duration: Int
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);
创建一个带有上下文的类的实例,并像这样调用任何地方
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);