Create Toast by a static method

2019-09-21 18:39发布

I use this code in all my app fragments and it should be better if I use a static method. How can I do it? This static method should also works on fragment, not only activities.

My not static showToast method:

public void showToast(String msg){
    Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}

SOLVED BY USING THIS STATIC METHOD thanks @KishanDhamat

public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();

}

3条回答
在下西门庆
2楼-- · 2019-09-21 18:51
public static void changeActivity(Context context,Class that){
    context.startActivity(new Intent(context, that));
} // my static method

  public void forgotPass(View view){
    Function.changeActivity(LoginActivity.this,ForgotPass.class);
} // my activity i want to change

This is my solution, hope it can help

查看更多
一夜七次
3楼-- · 2019-09-21 19:04

Use this:

public static void showToast(Context context, String text) {
    Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}

now for calling this method you should call like this:

ClassName.showToast(context,"text");

Here classname is class that containing static method.

查看更多
Ridiculous、
4楼-- · 2019-09-21 19:10
  • Change the signature of the method and add given Context as parameter
  • Change the signature of the method to make it static
  • Pass the Context as first argument of your Toast.makeText call
查看更多
登录 后发表回答