0

In my case, i have used the FragmentActivity and contain two page of fragment. initialize by this way.

public Fragment getItem(int position) {
    // getItem is called to instantiate the fragment for the given page.
    // Return a DummySectionFragment (defined as a static inner class
    // below) with the page number as its lone argument.
    switch (position) {
        case 0:
            return new Fragment1();
        case 1:
            return new Fragment2();
    }
    return null;
}

The action bar item is defined as below:

<item
    android:id="@+id/item_edit"
    android:icon="@android:drawable/ic_menu_edit"
    android:showAsAction="ifRoom"
    android:title="Edit"/>
<item
    android:id="@+id/item_save"
    android:icon="@android:drawable/ic_menu_save"
    android:showAsAction="withText|always"
    android:title="Save"/>

for example: i have one edittext at Fragment 1 and one edittext from Fragment 2.

<EditText
    android:id="@+id/editText1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
<EditText
    android:id="@+id/editText2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

and then the problem is how can i get the edittext data from the two fragment when i click the save action bar item. Thank you so much.

1 Answers1

1

One solution would be to define actionbar items for fragments themselves, not for host FragmentActivity, by overriding fragments' onCreateOptionsMenu In this case you just override onOptionsItemSelected inside fragment and have direct access to your EditText.

The second solution will be to define method like this:

class Fragment2 extends Fragment {
    // ... some code here

    public CharSequence getText() {
        return getView().findViewById(R.id.edittext2).getText();
    }
    // ... some code here
}

and access it in activity as the following:

Fragment fragment = getItem(1);
// ... some code here

// user clicked menu item:
if(fragment instanceof Fragment2) {
    CharSequence text = ((Fragment2)fragment).getText();
    // do whatever you want with text
}

Also you may define an interface with getText(), implement it in fragments, so you'll be able to get content from any desired fragment.

xapienz
  • 179
  • 5
  • Thank you for your answer, but can you explain more about the Fragment fragment = getItem(1); as this method is inside the class SectionsPagerAdapter extends FragmentPagerAdapter, also it will return a new fragment, how can get the page after it input the text at the editext? – user3489840 Apr 03 '14 at 06:29
  • In this case I would suggest to do the same as answered here: http://stackoverflow.com/a/15261142/2768194. You store references to created fragments and then call `Fragment fragment = adapter.getRegisteredFragment(viewPager.getCurrentItem())` – xapienz Apr 03 '14 at 07:48