How to call a method of a Fragment in an Activity?

Asked

Viewed 1,441 times

1

I need to use a Fragment method within an Activity, but I can’t pass a reference to that Activity. Can anyone help me?

That’s the whole idea:

    public class MinhaFragment extends Fragment{
    ...

      @Override
      public void onClick(View view) {
         if (view.getId() == R.id.fab) {
          Intent intent = new Intent(this.getContext(),MinhaActivity.class);
          startActivity(intent);
        }
      }

      public void showMessage(String message) {
         Snackbar snackbar = Snackbar.make(this.getView(), message, 
         Snackbar.LENGTH_LONG);
         snackbar.show();
      }
   }

This is my Activity

public class MinhaActivity extends Activity{
   ...

   @Override
   public void onClick(View view) {
     //chamar o metodo do fragment aqui por exemplo
     minhaFragment.showMessage("Teste");
   }

   ...
 }

Any help is welcome. Thanks in advance.

  • The method is the same or an example. The solution will depend on what he does.

  • In this case it is just an example, but the method has to send a string to the Fragment that called Activity.

2 answers

1

You can place this function in a model class and call instantiating:

Classe c = new Classe();
c.mostrarMsg(this, "mensagem")

You also need to pass the context

public void mostrarMsg(Context contexto, String mensagem) {
    Toast.makeText(contexto, mensagem, Toast.LENGTH_SHORT).show();
}

Note if you are going to call this function inside a button click, for example, you will have to create a variable Context out of scope:

final Context contexto = this;

public void onClick(View view) {
    c.mostrarMsg(contexto, "mensagem");
}

and use inside the click

0


Hello! : ) There is no ideal solution for this type of problem, at most one can identify names, for example, you can find out the name of Activity that called another Activity through the method getCallingActivity.

A solution unsaved would be to use a static method in Activity and pass Fragment to a static variable.

But most likely you are wanting to do something that there is a better way to do, if you want to pass information to the Fragment that called Activity and identify the moment that Activity is terminated, you should call this Activity with the method startActivityForResult and on Activity before closing it you should pass the information by intent with the method setResult

Example:

In the Fragment:

Intent i = new Intent(this, MinhaActivity.class);
getActivity().startActivityForResult(i, 1);

In the called Activity (Minhaactivity):

Intent retornoIntent = new Intent();
retornoIntent.putExtra("resultadoid",resultado);
setResult(Activity.RESULT_OK,retornoIntent);
finish();

And in the event that called Minhaactivity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String resultado = data.getStringExtra("resultadoid");
            //Momento exato quando a activity chamada por esse fragment é 
            //encerrada e o estado do app volta para esse fragment
        }
    }
}

That is, as there is no good reason to call a method from a Fragment that is not being used (because the current state of the app is in an Activity after the Fragment), we should not call a method from somewhere in the app that does not belong to the current state, instead, we should identify the exact time we returned to the previous state and when necessary use the necessary information of the state that has just been closed

Observing

It is very important to show here that Fragment will not have arrived at the method onActivityResult without Activity possessing that Fragment calling onActivityResult of this Fragment. Example assuming that the Fragment is inside Activitya:

Example - Activitya:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    fragmentA.onActivityResult(requestCode,resultCode,data); 
    //É necessário fazer isso para que o fragmentA tenha seu método onActivityResult chamado
}

Hugs :)

  • Thanks Digaopartner for the help and the explanation. I found another solution, but I think this one works better. Here ( https://groups.google.com/forum/#!topic/androidbrasil-dev/Ld_d972ybqm ) I show you the solutions I had, you can look and tell me what you think?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.