user3458049
user3458049

Reputation: 70

Passing values between Fragments in FragmentPagerAdapter

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

Answers (3)

Renjith Krishnan
Renjith Krishnan

Reputation: 2626

Solution as follows :

  1. First create an interface

    public interface SeekChangeInterface {
        public void sendChangedValue(int value)
    }
    
  2. Implement it your Activity where the FragmentPagerAdapter Belongs

  3. Create a object of interface in first fragment

    SeekChangeInterface  mSeekChangeInterface;
    
  4. Declare onAttach() in the first fragment

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        mSeekChangeInterface = (SeekChangeInterface )activity;
    }
    
  5. In seekbar change lisener call

    mSeekChangeInterface.sendChangedValue(valueofseekbar)
    
  6. Create a method in second fragment

    public void setSeekBarValue(int progress){
        seekBar.setProgress(progress);
    }
    
  7. Call this method from the Activity sendChangedValue()

     public void sendChangedValue(int progress){
         objectoffragnentpageradapter.getItem(1).setSeekBarValue(progress);
     }
    

Hope this will help you

Upvotes: 2

elmorabea
elmorabea

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

Patrick Dorn
Patrick Dorn

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

Related Questions