Skip to content Skip to sidebar Skip to footer

Adding Integers From Different Fragments In A ViewPager

I have a MainActivity that has a ViewPager with 3 fragments (FragA, FragB, FragC) In FragA, I declared an int a = 10; In FragB, I declared an int b = 20; In FragC, I have a TextVie

Solution 1:

Use your activity to help your fragments communicate...For example:

Add a getter method to return each fragment's integer value. Add a public String sum() method to your activity that would be something like:

public class MainActivity extends FragmentActivity {

ViewPager viewPager = null; 
MyAdapter adapter = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewPager = (ViewPager)findViewById(R.id.pager);    
    myAdapter = new MyAdapter(getSupportFragmentManager());
    viewPager.setAdapter(myAdapter);
}


public String sum(){
    return Integer.toString(((FragA)myAdapter.getItem(0)).getInt() + ((FragB)myAdapter.getItem(1)).getInt());
}

public class MyAdapter extends FragmentStatePagerAdapter {  
    public MyAdapter (FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = null;

        if (i == 0)
        {
            fragment = new FragA();
        }
        if (i == 1)
        {
            fragment = new FragB();
        }
        if (i == 2)
        {
            fragment = new FragC(); 
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return 3;
    }   
}

}

In your onClick() method within fragC(), all you need to do is set the text value to this sum when a click event occurs ->

textView.setText(((MainActivity)getActivity()).sum());

My parenthesis might be a bit off, but thats the general idea.

Edit:

public class FragA extends Fragment {

int a = 10;

public int getInt(){
   return a;
}

Solution 2:

Solved it. Thanks to Submersed

FragA

public class FragA extends Fragment{

    int a = 10;

    public int getInt() {

        return a;
    }
 ....

FragB

public class FragB extends Fragment{

        int b = 20;

        public int getInt() {

            return b;
        }
....

MainActivity

public String sum() {

    FragA FragA = new FragA();
    FragB FragB = new FragB();

    return Integer.toString(FragA.getInt() + FragB.getInt());
}

FragC

OnClickListener Click = new OnClickListener() { 

        @Override
        public void onClick(View v) {

            textView.setText(((MainActivity)getActivity()).sum());

        }
    };

Output on my textView when I click the "Add" button:

enter image description here


Post a Comment for "Adding Integers From Different Fragments In A ViewPager"