使用getSupportFragmentManager()时,findFragmentByTag()返回null

时间:2014-09-02 17:28:08

标签: android searchview android-actionbar-compat fragment-tab-host

我正在使用支持库ActionBar,因为我使用的是较旧的最低SDK。在活动中,我使用的是FragmentTabHost,因为我有3个标签。 ActionBar还有一个SearchView,因此在进行搜索时,第三个选项卡会被搜索结果切换出来。

我可以从SearchView获取输入,但是当我有搜索结果时,我无法切换出第3个标签。我用这个作为例子: Dynamically changing the fragments inside a fragment tab host?

我的问题是,当我尝试获取对第3个选项卡的引用,并且我使用getSupportFragmentManager()。findFragmentByTag()时,返回的片段始终为null。

我的基本容器,有助于在标签中交换多个片段:

    public class BaseContainerFragment extends Fragment{

    public void replaceFragment(Fragment fragment, boolean addToBackStack) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (addToBackStack) {
            transaction.addToBackStack(null);
        }
        transaction.replace(R.id.container_framelayout, fragment);
        transaction.commit();
        getChildFragmentManager().executePendingTransactions();
    }

    public boolean popFragment() {
        //Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
        boolean isPop = false;
        if (getChildFragmentManager().getBackStackEntryCount() > 0) {
            isPop = true;
            getChildFragmentManager().popBackStack();
        }
        return isPop;
    }
}

扩展BaseContainerFragment

的容器
public class LibraryContainerFragment extends BaseContainerFragment {

    private boolean mIsViewInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.e("test", "tab 1 oncreateview");
        return inflater.inflate(R.layout.container_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.e("test", "tab 1 container on activity created");
        if (!mIsViewInited) {
            mIsViewInited = true;
            initView();
//            setRetainInstance(true);
        }
    }

    private void initView() {
        Log.e("test", "tab 1 init view");

        replaceFragment(new LibraryFragment, false);

    }
}

用于切换片段的xml(container_fragment.xml):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container_framelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

我的主要活动:

public class BookSetup extends ActionBarActivity {

    // For accessing SlidingMenu library
    private SlidingMenu slidingMainMenu;
    private FragmentTabHost mTabHost;
    private SlidingMenu slidingContextMenuFavourites;
    private SlidingMenu slidingContextMenuMyPrayerBook;
    private SlidingMenu slidingContextMenuLibrary;
    private android.support.v4.app.FragmentManager fragmentManager;

    LibraryContainerFragment libraryContainerFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        // Settings for the clickable top-left button in the action bar
        android.support.v7.app.ActionBar bar = getSupportActionBar();

        bar.setDisplayHomeAsUpEnabled(false);
        bar.setHomeButtonEnabled(true);
        bar.setIcon(R.drawable.main_menu);

        // Setting up tabbed navigation
        bar.setDisplayShowTitleEnabled(false);


        // Setting up tabs    
        fragmentManager = getSupportFragmentManager();
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, fragmentManager, R.id.realtabcontent);



        // Add tabs
        mTabHost.addTab(mTabHost.newTabSpec("Favourites").setIndicator(getString(R.string.favourites) ),
                FavouritesFragment.class, null);

        mTabHost.addTab(mTabHost.newTabSpec("My Book").setIndicator(getString(R.string.my_book) ),
                MyBookFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("Library").setIndicator(getString(R.string.library) ),
                LibraryContainerFragment.class, null);

        mTabHost.setCurrentTab(2);


        //mTabHost.

        // Creates a sliding animation when activity is started
        overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
    }



        @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu_with_search_context_menu, menu);


        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        //SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();



        final MenuItem searchMenuItem = menu.findItem(R.id.action_search);
        searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(searchMenuItem);
        //searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getComponentName()));
        //searchView.requestFocus();
        searchView.requestFocusFromTouch();

        //searchView.setIconifiedByDefault(true);


        // Listener for the search input found in the action bar, when the magnifying glass is
        // clicked
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            // Activated when a search string is submitted
            @Override
            public boolean onQueryTextSubmit(String query) {
                // TODO : query is the text from the search view after you clicked search

                if(query != null){


                    // If results are found, then switch the fragments
                    if(!sectionsFound.isEmpty()){

                        // Initialize the search fragment and send bundles of data to it
                        SearchLibraryResultFragment fragment = new SearchLibraryResultFragment();
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList("values",
                                (ArrayList<? extends Parcelable>) sectionsFound);
                        bundle.putStringArrayList("names", sectionNames);
                        fragment.setArguments(bundle);

                        mTabHost.setCurrentTab(2);
                        libraryContainerFragment = (LibraryContainerFragment)fragmentManager.findFragmentByTag("Library");


                       ((BaseContainerFragment) libraryContainerFragment.getParentFragment() ).replaceFragment(fragment,true );


                return true;
            }


        });

    }
}

这是在BookSetup.java中始终返回null的行:

((BaseContainerFragment) libraryContainerFragment.getParentFragment() ).replaceFragment(fragment,true );

1 个答案:

答案 0 :(得分:0)

您使用ChildFragmentManager替换Fragments权利吗?

这可能是你的问题,而不是

libraryContainerFragment = (LibraryContainerFragment)fragmentManager.findFragmentByTag("Library");

使用

libraryContainerFragment = (LibraryContainerFragment) getChildFragmentManager().findFragmentByTag("Library");