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 {
ViewPagerviewPager=null;
MyAdapteradapter=null;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
myAdapter = newMyAdapter(getSupportFragmentManager());
viewPager.setAdapter(myAdapter);
}
public String sum(){
return Integer.toString(((FragA)myAdapter.getItem(0)).getInt() + ((FragB)myAdapter.getItem(1)).getInt());
}
publicclassMyAdapterextendsFragmentStatePagerAdapter {
publicMyAdapter(FragmentManager fm) {
super(fm);
}
@Overridepublic Fragment getItem(int i) {
Fragmentfragment=null;
if (i == 0)
{
fragment = newFragA();
}
if (i == 1)
{
fragment = newFragB();
}
if (i == 2)
{
fragment = newFragC();
}
return fragment;
}
@OverridepublicintgetCount() {
return3;
}
}
}
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:
publicclassFragAextendsFragment {
int a = 10;
publicintgetInt(){
return a;
}
Solution 2:
Solved it. Thanks to Submersed
FragA
publicclassFragAextendsFragment{
int a = 10;
publicintgetInt() {
return a;
}
....
FragB
publicclassFragBextendsFragment{
int b = 20;
publicintgetInt() {
return b;
}
....
MainActivity
public String sum() {
FragAFragA=newFragA();
FragBFragB=newFragB();
return Integer.toString(FragA.getInt() + FragB.getInt());
}
FragC
OnClickListenerClick=newOnClickListener() {
@OverridepublicvoidonClick(View v) {
textView.setText(((MainActivity)getActivity()).sum());
}
};
Output on my textView when I click the "Add" button:
Post a Comment for "Adding Integers From Different Fragments In A Viewpager"