Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/207.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的短格式toast_Java_Android_Android Studio_Kotlin - Fatal编程技术网

Java中的短格式toast

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

当我用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 = 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);