Passage of values between Fragment and Activity

Asked

Viewed 153 times

3

I have a fragment that consists of several buttons. The goal is that when I press one of these buttons the fragment disappear and pass the value associated with that button to the activity that is in the background. What is happening is that when I press the button, the fragment does not disappear and the activity does not receive the value of the button. I am using Callback.I have no mistake or exception.

Fragment Code:

(...)
 public HoroscopeChoice() {}
    /******************************
     * Callback
     ********/
    public static void setOnInfoChangedListener(OnInfoChangedListener callback) {
        mCallback = callback;
    }

    public interface OnInfoChangedListener {
        public void onInfoChanged(String horosocopo);
     }
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_horoscope_choice,
                container, false);

        Button aquarius;
        aquarius  = (Button) view.findViewById(R.id.aquarius1);

        final int id = view.getId();

        View.OnClickListener onClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String horoscopo = onClick2(v.getId());
                Log.d("HoroscopeChoice", "ao clicar no botao->"+horoscopo);
                mCallback.onInfoChanged(horoscopo);
            }
        };

        aquarius.setOnClickListener(onClickListener);
(...)

Activity Code:

(...)
public void onInfoChanged(String horoscopo) {
        Log.d("SchedulerActivity","OnInfoChanged na Scheduler->"+horoscope);

        mHoroscopeDisplay = (TextView) findViewById(R.id.dailyHoroscope4);
        mHoroscopeDisplay.setText(horoscopo);
    }

When I do Log.d in the fragment I get the horoscope, already in the activity appears empty. What I need to do?

  • Friend, here’s a solution to your problem: http://answall.com/questions/129013/pega-dados-de-3-fragments/129380#129380

3 answers

3

Hello, prothfind. To get started, the idea is for your Activity to implement an interface that Fragment knows and calls. So, let’s create such interface that will be called when there was the click on Fragment:

public interface OnFragmentButtonClickListener  {
    public void onButtonClick();
}

And we will then have Activity inherit this interface and implement the method:

public class MinhaActivity extends AppCompact implements OnFragmentButtonClickListener {

    //... Outros métodos comuns da Activity

    public void onButtonClick() {
       //O botão do fragment foi clicado, faça o que tem que fazer na activity!
    }

}

Right, in the method onAttach() from your Fragment , which is called during the Fragment lifecycle when a Fragment is attached to Activity, capture the Activity using polymorphism to get in hands an instance give Onfragmentbuttonclicklistener. Thus:

public void FragmentTwo extends Fragment {

   OnFragmentButtonClickListener onFragmentButtonClickListener

   @Override
    public void onAttach(Context context) {
        if(context instanceof OnFragmentButtonClickListener) {
            onFragmentButtonClickListener = (OnFragmentButtonClickListener) context;
        }
        super.onAttach(context);
    }

    //Métodos comuns ao fragment
}

Now, on the onClickListener of your button call the interface that is implemented by Activity so that the Activity can match the click on Fragment:

fragmentButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       //onFragmentButtonClickListener.onButtonClick(); Lembrando que onFragmentButtonClickListener pode ser null caso a activity não implemente a interface.
    } 
});

Why do I prefer this answer to João Gouveia’s? By abstraction. In João Gouveia’s answer you are holding your Fragment to Myactivity and this can bring you some problems, besides breaking some of the good practices. It may be that your Fragment is attached to several other activities besides Myactivity. It may also happen that your Fragment in the future will no longer be attached to Myactivity, which will generate a reference search for maintenance. Working with interfaces makes your code more uncoupled and scalable. Abs!

1

You can create a variable in your Activity, in addition to a Setter, and "settar" its value from within the Fragment:

public class MyActivity extends Activity {
    private String horoscopo;

    public void setHoroscopo(String horoscopo) {
        this.horoscopo = horoscopo;
    }
}    

and in Fragment you call:

((MyActivity) getActivity).setHoroscopo(horoscopo);
  • It’s not a good idea because it attaches that Fragment to that specific Activity. If you want to reuse in another Activity (which is one of the main advantages of Fragment), you will not be able.

  • I disagree that this is one of the main advantages of Fragment, usually Fragments are used in a specific way even (coupled to a specific Activity). Anyway you can always generalize: if (getActivity instaceof Myactivity) ...

  • That’s not generalizing. You’re going from one to two. If your idea of extensibility is the use of instanceof, you still don’t quite understand the The solid.

0


The only thing missing from my fragment that I discovered later was:

dismiss()

so he disappears when you press the button.

Browser other questions tagged

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