无需按钮即可重新创建条件片段

时间:2019-06-26 06:47:33

标签: android android-layout android-fragments

在我的应用程序中,有四个带有片段的ButtonNavigationView选项卡,我希望其中每一个在单击它们时刷新2个,而另2个在我每次单击它们时不刷新,如何获得?

家庭活动

final Fragment factorsFragment = new FactorsFragment();
    final Fragment newFactorFragment = new NewFactorFragment();
    final Fragment productsFragment = new ProductsFragment();
    final Fragment checkList = new CheckList();

    final FragmentManager fm = getSupportFragmentManager();
    Fragment active = newFactorFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        fm.beginTransaction().add(R.id.fragment_container, productsFragment, "4").hide(productsFragment).commit();
        fm.beginTransaction().add(R.id.fragment_container, factorsFragment, "3").hide(factorsFragment).commit();
        fm.beginTransaction().add(R.id.fragment_container, checkList, "2").hide(checkList).commit();
        fm.beginTransaction().add(R.id.fragment_container, newFactorFragment, "1").commit();

        SQLiteStudioService.instance().start(this);



    }
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {
                case R.id.navigation_home:
                    fm.beginTransaction().hide(active).show(factorsFragment).commit();
                    active = factorsFragment;
                    return true;
                case R.id.navigation_dashboard:
                    fm.beginTransaction().hide(active).show(newFactorFragment).commit();
                    active = newFactorFragment;
                    return true;
                case R.id.navigation_notifications:
                    fm.beginTransaction().hide(active).show(productsFragment).commit();
                    active = productsFragment;
                    return true;
                case R.id.navigation_checklist:
                    fm.beginTransaction().hide(active).show(checkList).commit();
                    active = checkList;
                    return true;
            }

            return false;
        }
    };

我希望在不添加swiperefreshlayout或自定义刷新按钮的情况下刷新factorFragment和productFragment

我的问题是我所有的片段都不会在选项卡更改时刷新,因为我只是在显示和隐藏它们,但我希望其中两个刷新。

1 个答案:

答案 0 :(得分:1)

在各个片段的onResume中调用factorFragment和productFragment的所有功能。更改将反映在您再次在onResume中调用方法时。

片段具有偏移量。因此,如果您要在活动中加载一个片段,则接下来的几个片段(取决于您设置的内容或默认偏移量)也会被初始化。因此,在onResume中调用函数是明智的。