2015-02-18 56 views
0

getItem()位置並非總是正確!有時它會顯示0,1,2,3,4,那麼如果我回去顯示不同的位置(4,2,3,1,0)。如果我需要位置傳遞到數組列表/樹形圖,那麼使用「位置」的正確方法是什麼?將位置作爲參數傳遞給Fragment在FragmentPagerAdapter中

02-18 20:07:22.453 11479-11479/com.app E/aaa﹕ position created:0 
02-18 20:07:22.453 11479-11479/com.app E/aaa﹕ position created:1 
02-18 20:07:29.053 11479-11479/com.app E/aaa﹕ position created:2 
02-18 20:07:35.503 11479-11479/com.app E/aaa﹕ position created:0 

行:

return SingleCard.newInstance(get_all_cards_as_objects().get(position)); 

需要的正確位置,不會被渲染到內存中的一個!我需要片段中的數據隨實際頁面位置而變化。它會根據實際的頁面位置知道要抓取的數據(來自地圖)。

final ViewPager pager = (ViewPager) findViewById(R.id.pager); 
     this.parent_nested_fragment_activity = this; 

     pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()){ 
      private final int PARENT_COUNT = get_all_cards_as_objects().size(); 

      @Override 
      public Object instantiateItem(ViewGroup container, final int position) { 
       Object obj = super.instantiateItem(container, position); 
       pager.setObjectForPosition(obj, position); 
       return obj; 
      } 

      @Override 
      public Fragment getItem(int position) { 
      Toast.makeText(CardDealer.this,"Selected page position: " + position, Toast.LENGTH_SHORT).show(); 
      Log.e("aaa", "position created:" + position); 
        return SingleCard.newInstance(get_all_cards_as_objects().get(position)); 
      } 

我喜歡他的問題,但這個問題的答案並沒有幫助: FragmentPagerAdapter getItem wrong position

我也不清楚如何實現這個答案在我的片段:getItem() calling multiple time in FragmentPagerAdapter

就像這樣: Weird dissappearing Fragments with FragmentPagerAdapter

基本上我已經研究過:

pager.getCurrentItem(); 

如何通過getItem()將其傳遞到已創建的片段中?

return SingleCard.newInstance(get_all_cards_as_objects().get(pager.getCurrentItem())); 

回答

1

好吧我想通了,我正在創建的實際片段有一個問題。我在我的SingleCard片段中使用了一個靜態的int。將其更改爲非靜態的int修復了問題!

//problem: 
    private static int page; 
    //solution: 
    private int page; 

public class SingleCard extends Fragment { 
    public static SingleCard newInstance (int sent_in_position) { 
     SingleCard fragmentFirst = new SingleCard(); 
     Bundle args = new Bundle(); 
     args.putInt("position", sent_in_position); 
     fragmentFirst . setArguments(args); 
     return fragmentFirst; 
    } 

@Override 
public void onCreate (Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    page = getArguments().getInt("position", 0); 
} 
相關問題