-3

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();

}

Hasta'98
  • 184
  • 2
  • 9

3 Answers3

5

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.

Kishan Dhamat
  • 3,588
  • 1
  • 23
  • 35
3
  • 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
Mena
  • 46,817
  • 11
  • 84
  • 103
0
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

MindVN
  • 81
  • 1
  • 3