2015-04-27 22 views
0

我想在最後一頁中設置visible一個button,但最後一個元素不會調用片段constructor。 (我調試它)最後一項FragmentStatePagerAdapter

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

這是可能的,因爲你的FragmentStatePagerAdapter重用存在Fragment存在。這些嘗試,使其工作:

  • 設置按鈕,在你的適配器的getItem()方法的知名度,而不是在onCreateView()

  • 添加一個代碼,使按鈕INVISIBLE以及 - 您必須決定每次您的Fragment重複使用時按鈕的可見性。

+0

非常感謝您的答案。錯誤是愚蠢的,getNquestions返回計數問題和getItem(Int i)從0開始。然後最後一個項目是3,總任務是4.對不起。 – user3612445

+0

對你有好處。但是,當頁數增加時,您可能會遇到一些麻煩。如果發生,請使用我的答案。 – hoonj