Zubayr
Zubayr

Reputation: 456

Changing variable's value of fragment from the activity

I have an activity like this:

enter image description here

There are 2 buttons A and B on toolbar and a frame for fragment to take over. Say I have a string variable named button_type in fragment.

I want to have a system so that when I click button A in activity, the button_type in fragment sets to A and when I click button B in activity, the button_type in fragment sets to B. How to do this?

Please note that I may click the buttons (A,B) when the fragment is already active (its not like after I click one button, the fragment comes.)

Thanks in advance.

Edit: Currently I am trying this:

In MainActivity I get similar string button_type and set it as A or B according as button click and use the method:

public String getData(){return button_type;}

And in fragment I use: button_type= activity.getData(); in onViewCreated.

But it only seems to have the initial set value of A and B (which is A) and does not change when another button is clicked.

Upvotes: 0

Views: 1731

Answers (2)

Create an interface with methods onClickA(String buttonType) and onClickB(String buttonType). Then create an object that implements this interface (or make fragment implement this interface by itself). I'll call this object listener. call setButtonType(String buttonType) in listener methods implementation. Then pass your listener to activity (you can get an instance of parent activity in fragment with getActivity() and cast it to your activity class) and in onClickListener of button A (in activity) call listener.onClickA(yourString) and do the same thing for button B.

Upvotes: 1

Papan
Papan

Reputation: 382

I think the best way if you use an interface for managing text in the fragment. the fragment will implement the interface. When the button click call the function in the fragment which is implemented by fragment.

Another way you can create an object of the fragment using findFragmentByTag() or findFragmentById() and then call the function in the fragment which handles the text.

Upvotes: 2

Related Questions