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

2023-12-25

我正在使用支持库 ActionBar,因为我使用的是较旧的最小 SDK。在活动中,我使用 FragmentTabHost 因为我有 3 个选项卡。 ActionBar 还有一个 SearchView,因此当进行搜索时,第三个选项卡将与搜索结果一起切换。

我能够从 SearchView 获取输入,但当我有搜索结果时,我无法切换第三个选项卡。我以此为例:动态更改片段选项卡主机内的片段? https://stackoverflow.com/questions/18120510/dynamically-changing-the-fragments-inside-a-fragment-tab-host

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

我的基本容器有助于在选项卡中交换多个片段:

    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 );

您正在使用ChildFragmentManager来代替你的Fragments right?

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

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

use

libraryContainerFragment = (LibraryContainerFragment) getChildFragmentManager().findFragmentByTag("Library");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 getSupportFragmentManager() 时 findFragmentByTag() 返回 null 的相关文章

随机推荐

  • 将平面对象数组转换为嵌套对象

    我有以下数组 实际上来自后端服务 const flat Item id a name Root 1 parentId null id b name Root 2 parentId null id c name Root 3 parentId
  • C++ time_t 问题

    我在 C VS 2008 中的日期管理方面遇到问题 根据MSDN 规范 http msdn microsoft com en us library 323b6b3k 28v VS 90 29 aspx time t代表 自 1970 年 1
  • Erlang ping 节点问题

    我在 erlang shell 中做了 1 gt node nonode nohost But 2 gt net adm ping node pang 为什么 什么问题 为什么不打乒乓球 谢谢 你没有启动 Erlang name or sn
  • 使用 k 均值算法进行异常值检测

    我希望你能帮助我解决我的问题 我正在尝试使用 kmeans 算法来检测异常值 首先 我执行算法并选择那些距聚类中心距离较远的对象作为可能的异常值 我不想使用绝对距离 而是想使用相对距离 即对象到聚类中心的绝对距离与聚类中所有对象到其聚类中心
  • 如何检测 scanf() 末尾的空格或换行符?

    我正在编写一个程序 我必须接受来自用户的命令 就像用户可以在其中设置环境变量值的 shell 一样 我遇到的问题是如果用户输入set var var value我需要知道用户输入了一个空格而不仅仅是set并按下 Enter 键 这是一个不同
  • Beanshell 不允许我将 jar 添加到“默认”JRE 类加载器吗?

    我有一个问题豆壳 http www beanshell org manual bshmanual html我在任何地方都找不到答案 我只能通过以下两种方式之一运行 Beanshell 脚本 其中Classpath是在调用Beanshell之
  • 是我的类内装饰器不够 Pythonic 还是 PyCharm 在 lint 警告方面不够智能?

    我想在类中定义一个装饰器 我不想将它定义为一个单独的 独立的函数 因为这个装饰器是专门针对这个类的 我想将相关的方法保留在一起 这个装饰器的目的是检查一些先决条件 特别是成员变量持有的数据库连接 SSH连接等是否仍然可用 如果不是 则不会调
  • imshow(img, cmap=cm.gray) 显示 128 值的白色

    我正在从 MatLab 转向 python 并使用 imshow 函数 我似乎无法理解为什么它不将值 128 显示为灰色 而我选择了 cmap 为灰度 看起来它使用最高 128 和最低值的灰度 我希望它使用 0 255 的灰度 我怎么做 U
  • Objective-C – UILocalNotification AlertBody 长度

    我正在寻找一些文档来找到最大长度alertBody of a UILocalNotification之前它会被剪辑在通知中心 横幅 或弹出警报中 I haven t found any specific limit documented H
  • 我应该使用哪个 HTML5 标签来标记作者姓名?

    例如博客文章或文章
  • 如何将对象从其基类转换为其子类

    我有课User这是类的子类PFUser class User PFUser var isManager false 在我的一种方法中 我收到了PFUser对象 我想将其转换为User object func signUpViewContro
  • tf.zeros() 的动态大小(与无尺寸的占位符一起使用)

    考虑以下代码 x tf placeholder float shape 42 4 y tf zeros 42 4 float xy stacked tf concat 1 x y print x get shape print y get
  • Flutter PDF 中古吉拉特语字体渲染问题

    我正在使用 Flutter 2 0 开发移动应用程序 整个应用程序采用古吉拉特语 应用程序已准备就绪 所有文本都在应用程序中完美呈现 但是当我从屏幕上的数据生成 pdf 时 古吉拉特语字体不正确渲染 我正在使用插件 pdf 3 0 1 fo
  • 指定默认下载文件夹 - 可能使用 JavaScript?

    我们目前正在开发一个基于网络的应用程序 该应用程序需要通过浏览器下载文件 理想的情况是让这些文件最终位于文件系统上的特定位置 有没有办法使文件保存和文件打开对话框默认为特定文件夹 例如 USER Downloads MyApp 我不希望它成
  • Nanoc布局编译规则

    我正在使用nanoc 我希望我的index html指向特定的布局 所以我创建了该布局 它被称为nosidebar html 我的规则如下 compile index html do layout nosidebar end 这似乎不起作用
  • 如何使用 vue-test-utils 打开 bootstrap-vue 模式?

    我使用 bootstrap 作为我的设计框架 并且一直在使用 bootstrap vue 现在我想实现一些测试来配合我的组件 我正在编写一个非常简单的测试来确保打开模式 我在 vue test utils 中使用什么来打开 bootstra
  • Spring security 具有多个登录页面

    我正在使用 Spring security 使用用户名和密码来安全登录应用程序管理部分 但现在我的客户需要为应用程序客户端部分提供另一个登录屏幕 他们将在其中拥有自己的用户名 密码来登录客户端部分 到目前为止 我已经使用以下 spring
  • 四次函数的根

    我在进行一些高级碰撞检测时遇到了一种情况 需要计算四次函数的根 我使用法拉利的通用解决方案编写了一个似乎运行良好的函数 如下所示 http en wikipedia org wiki Quartic function Ferrari 27s
  • VBA如何在没有.Select的情况下复制单元格的内容

    我正在写一个方法 可以采用Target并将单元格完全粘贴到另一个单元格中 该单元格是一个带有一些奇特格式的运输标签 我有办法做到吗 原来我有这个 Worksheets Label Range A1 Value Worksheets Get
  • 使用 getSupportFragmentManager() 时 findFragmentByTag() 返回 null

    我正在使用支持库 ActionBar 因为我使用的是较旧的最小 SDK 在活动中 我使用 FragmentTabHost 因为我有 3 个选项卡 ActionBar 还有一个 SearchView 因此当进行搜索时 第三个选项卡将与搜索结果