Reputation: 70
In FragmentPageradapter
I have 3 fragments. In first two fragments there is a SeekBar
. When either of the SeekBar
changes its value in fragment1
, I want to change the value ofSeekBar
which is inside fragment2
. How can I achieve It?
Upvotes: 2
Views: 2364
Reputation: 2626
Solution as follows :
First create an interface
public interface SeekChangeInterface {
public void sendChangedValue(int value)
}
Implement it your Activity where the FragmentPagerAdapter
Belongs
Create a object of interface in first fragment
SeekChangeInterface mSeekChangeInterface;
Declare onAttach()
in the first fragment
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mSeekChangeInterface = (SeekChangeInterface )activity;
}
In seekbar change lisener call
mSeekChangeInterface.sendChangedValue(valueofseekbar)
Create a method in second fragment
public void setSeekBarValue(int progress){
seekBar.setProgress(progress);
}
Call this method from the Activity sendChangedValue()
public void sendChangedValue(int progress){
objectoffragnentpageradapter.getItem(1).setSeekBarValue(progress);
}
Hope this will help you
Upvotes: 2
Reputation: 3263
One way to go is have your activity be responsible for the communication, meaning that when the seekbar changes, the fragment should do something like this:
((YourActivity) getActivity()).notifySeekBarValueChanged(int);
And in your activity
private void notifySeekBarValueChanged(int value) {
MyFragment frag = getSupportFragmentManager().findFragmentById(int);
frag.seekBarValueChangedTo(value);
}
Another way to go is to use some sort of messaging mechanism between your fragments like EventBus or Otto
Upvotes: 1
Reputation: 768
Do not hold a reference to the fragment and try to update it this way. The fragment may be null, or not attached yet.
Try to use the Activity. Implement an setter in your activity and use it in the seekbar change listener to set the current value. In the other fragment use the activity to restore the value.
Something like:
((MyActivity) getActivity()).setSeekValue(40);
((MyActivity) getActivity()).getSeekValue();
note that this is not a perfect solution as the activity can be null too (add null checks) and you have to cast to MyActivity. But i think it is a usable quick solution.
Hope this helps
Upvotes: 1