How to call a method of a fragment in an activity?

1

I need to use a method of a fragment within an activity, but I can not pass a reference to this activity. Can someone help me?

The idea is this:

    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.

    
asked by anonymous 14.11.2017 / 23:31

2 answers

0

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

A solution not recommended would be to use a static method in activity and pass the 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 the activity and identify the moment that activity ends, you should call this activity with the startActivityForResult and in activity before closing it you should pass the information by intent with method setResult

Example:

No fragment:

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

In the activity that was called (MinhaActivity):

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

And in the fragment 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, since there is no good reason to call a method of a fragment that is not being used (since 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 must identify the exact moment that we return to the previous state and when necessary to use the necessary information of the state that has just been closed

Note

It is very important to show here that Fragment will not have reached the onActivityResult method without the Activity that has this Fragment calling onActivityResult of this Fragment. Example assuming FragmentA is within 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:)

    
16.11.2017 / 16:21
1

You can put this function in a model class and call by 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 single 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 within the click

    
14.11.2017 / 23:36