简体   繁体   中英

Android callback from activity to fragment

I have "onOptionsItemSelected" method overrided in main activity, i want to notify my list when i tap on action bar items to change language on list. how do i make callback from MainActivity.java to my ListFragment.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_exit) {
        finish();

        return true;
    } else if (id == R.id.action_en) {
        changeLanguageToEn();

        return true;
    } else if (id == R.id.action_ge) {
        changeLanguageToGe();

        return true;
    }

    return super.onOptionsItemSelected(item);
}

Assuming your fragment is called MyListFragment.java and has a method called changeLanguage() I usually use the following method to get the current fragment:

FragmentManager fragmentManager = getSupportFragmentManager();
// (if you're not using the support library)
// FragmentManager fragmentManager = getFragmentManager();
for (Fragment fragment : fragmentManager.getFragments()) {
    if (fragment != null && fragment.isVisible() && fragment instanceof MyListFragment) {
        ((MyListFragment) fragment).changeLanguage();
    }
}

在您的ListFragment中 ,您可以为菜单充气。

You do this using the Activity - Fragment interface Listener pattern. android docs

to read more about it. here they are doing opposite of what you are..fragment is callbacking to an activity, using same pattern.

you can also use FragmentManager and find said fragment and then call its public method you can also TypeCast using getActivity and call activity methods from fragment. [but the interface pattern will solve and deouple your code nicely]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM