为什么getFragmentManager()。findFragmentByTag(String.valueOf(SOME INTEGER))不工作?

时间:2013-08-14 10:57:26

标签: android android-fragments

我有一堆Fragments并尝试使用getFragmentManager()。findFragmentByTag()方法返回堆栈。

如果以这种方式调用,此方法会返回对象:

getFragmentManager().findFragmentByTag("3")

CountingFragment {40d68d00#2 id = 0x7f090000 3}

但如果我将变量用作参数,它将返回NULL:

                int nextLevel = currentPositionInTheStack+1;
                getFragmentManager().findFragmentByTag(String.valueOf(nextLevel));

OR

                int nextLevel = currentPositionInTheStack+1;
                String nextLevelTag = "a" + nextLevel;
                getFragmentManager().findFragmentByTag(nextLevelTag);

有关为何发生这种情况的任何建议,

提前谢谢

2 个答案:

答案 0 :(得分:0)

你如何设置你的fragmentTag? 这样的事情是必要的:

ft.add(fragmentContainerId, mfragment, String.valueOf(++currentPositionInTheStack));

答案 1 :(得分:0)

已经想出如何在堆栈中前进和后退:

对于向前导航,如果下一个片段已经存在,则使用hide()和show()方法:

        Button button = (Button)findViewById(R.id.new_fragment);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                CountingFragment currentFragment = (CountingFragment)getFragmentManager().findFragmentByTag(String.valueOf(currentPositionInTheStack));
                int nextLevel = currentPositionInTheStack+1;
                currentPositionInTheStack++;
                CountingFragment nextFragment = (CountingFragment)getFragmentManager().findFragmentByTag(String.valueOf(currentPositionInTheStack));
                if (nextFragment == null) {
                    addFragmentToStack();

                }
                else
                {
                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.hide(currentFragment);
                    fragmentTransaction.show(nextFragment);
                    fragmentTransaction.commit();

                }

            }
        });

对于后退导航,必须覆盖onBackPressed方法:

        public void onBackPressed() {
            super.onBackPressed();  
            currentPositionInTheStack--;
            Log.d("Current Position In The Stack", String.valueOf(currentPositionInTheStack));
            if (currentPositionInTheStack ==0) {
                //do smth
            } }

原始问题中的Fragment为NULL,但是应该为null,为什么它返回Object,如果我执行了getFragmentManager()。例如,findFragmentByTag(“3”)不清楚。