最后一项FragmentStatePagerAdapter

时间:2015-04-27 09:03:56

标签: android fragmentstatepageradapter

我想在最后一页设置visible一个button,但最后一个元素不会调用片段constructor。 (我调试了它)

public Fragment getItem(int i) {
        Fragment fragment = new DemoObjectFragment();
        Bundle args = new Bundle();
        args.putParcelable(DemoObjectFragment.ARG_OBJECT,        check.getQuestionWithId(i));


        if(check.getNQuestions()==i)
            args.putBoolean(DemoObjectFragment.FINAL_QUEST,true);

@Override
    public int getCount() {

        return check.getNQuestions();
    }

和DemoObjectFragment:

 public static class DemoObjectFragment extends Fragment {

        public static final String ARG_OBJECT = "QUESTION";
        public static final String FINAL_QUEST = "FINAL_QUEST";

        public static final int requestCode_AnswerActivity = 1;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {


            View rootView = inflater.inflate(R.layout.question_fragment, container, false);

            Bundle args = getArguments();
            final Question quest = args.getParcelable(ARG_OBJECT);

            ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                    quest.getContent());

            if(args.getBoolean(FINAL_QUEST)) {

                Button finish_test = (Button) rootView.findViewById(R.id.button_finish_test);
                finish_test.setVisibility(View.VISIBLE);
           }
        }
    }

感谢。

1 个答案:

答案 0 :(得分:1)

这可能是因为FragmentStatePagerAdapter 重新使用现有Fragment。尝试这些使它工作:

  • 在适配器的getItem()方法中设置按钮的可见性,而不是onCreateView()

  • 添加代码以生成按钮INVISIBLE - 每次重复使用Fragment时,您必须确定按钮的可见性。