2017-02-25 44 views
0

對於最後2天我花了我所有的時間來嘗試找到一個解決方案,在一個ViewPager與一個奇怪的問題片段。所有片段都包含一個listview(它有自己的適配器)。爲什麼viewPager的中間選項卡從不爲自己調用onCreateView?

這裏的情況是:

  • 我有實例化一個viewpager和它的適配器和包含對象適配器類的活動。

公共類SellerActivity擴展AppCompatActivity {

/** 
* The {@link android.support.v4.view.PagerAdapter} that will provide 
* fragments for each of the sections. We use a 
* {@link FragmentPagerAdapter} derivative, which will keep every 
* loaded fragment in memory. If this becomes too memory intensive, it 
* may be best to switch to a 
* {@link android.support.v4.app.FragmentStatePagerAdapter}. 
*/ 
private SectionsPagerAdapter mSectionsPagerAdapter; 
private FirebaseAuth mAuth = FirebaseAuth.getInstance(); 

/** 
* The {@link ViewPager} that will host the section contents. 
*/ 
private ViewPager mViewPager; 

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.vpContainer2); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs2); 
    tabLayout.setupWithViewPager(mViewPager); 

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 

     // This method will be invoked when a new page becomes selected. 
     @Override 
     public void onPageSelected(int position) { 
      mViewPager.setCurrentItem(position); 
      mSectionsPagerAdapter.getItem(position); 
      Toast.makeText(SellerActivity.this, 
        "Selected page position: " + position, Toast.LENGTH_SHORT).show(); 
     } 

     // This method will be invoked when the current page is scrolled 
     @Override 
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 
      // Code goes here 
     } 

     // Called when the scroll state changes: 
     // SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING 
     @Override 
     public void onPageScrollStateChanged(int state) { 
      // Code goes here 
     } 
    }); 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_shop, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    Intent i = new Intent(SellerActivity.this, MainActivity.class); 
    if (id == R.id.action_home) { 
     startActivity(i); 
     finish(); 
     return true; 
    } 
    if (id == R.id.action_logout) { 
     mAuth.signOut(); 
     startActivity(i); 
     finish(); 
     return false; 
    } 

    return super.onOptionsItemSelected(item); 
} 
/** 
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
* one of the sections/tabs/pages. 
*/ 
public class SectionsPagerAdapter extends FragmentPagerAdapter { 

    public SectionsPagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a PlaceholderFragment (defined as a static inner class below). 
     return SellerFragment.newInstance(position + 1, "1"); 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     switch (position) { 
      case 0: 
       return "En Attente"; 
      case 1: 
       return "En cours"; 
      case 2: 
       return "Terminées"; 
     } 
     return null; 
    } 
} 
  • 我有那麼它看起來像這樣一個片段:

公共類SellerFragment擴展片段{

private String title; 
private int page; 

private AllOrders allOrders; 

final List<CommandItemForSeller> orders = new ArrayList<>(); 
final LinkedHashMap<String, Order> saveOrders = new LinkedHashMap<>(); 

public SellerFragment(){ 

} 

// newInstance constructor for creating fragment with arguments 
public static SellerFragment newInstance(int page, String title) { 
    SellerFragment fragmentFirst = new SellerFragment(); 
    Bundle args = new Bundle(); 
    args.putInt("someInt", page); 
    args.putString("someTitle", title); 
    fragmentFirst.setArguments(args); 
    return fragmentFirst; 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    page = getArguments().getInt("someInt", 0); 
    title = getArguments().getString("someTitle"); 
    allOrders = new AllOrders(); 
    setRetainInstance(true); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_seller, container, false); 
    TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel); 
    tvLabel.setText(page + " -- " + title); 

    DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("orders"); 
    ChildEventListener childEventListener = new ChildEventListener() { 
     @Override 
     public void onChildAdded(DataSnapshot dataSnapshot, String s) { 


      for (DataSnapshot orders : dataSnapshot.getChildren()) { 

       String orderString = orders.getValue(String.class); 

       //allOrders.addOrder(new Order(orderString, orders.getKey().substring(orders.getKey().length() - 4, orders.getKey().length()))); 
       saveOrders.put(orders.getKey(), new Order(orderString, orders.getKey().substring(orders.getKey().length() - 4, orders.getKey().length()))); 

      } 

     } 

     @Override 
     public void onChildChanged (DataSnapshot dataSnapshot, String s){ 

     } 

     @Override 
     public void onChildRemoved (DataSnapshot dataSnapshot){ 

     } 

     @Override 
     public void onChildMoved (DataSnapshot dataSnapshot, String s){ 

     } 

     @Override 
     public void onCancelled (DatabaseError databaseError){ 

     } 
    }; 

    myRef.addChildEventListener(childEventListener); 
    orders.clear(); 

    allOrders.clear(); 
    allOrders.addAllOrders(saveOrders.values()); 
    List<Order> selectedOrders = allOrders.getItemsOrderedByStatus(page); 
    for (int i = 0; i < selectedOrders.size(); i++) { 
     orders.add(new CommandItemForSeller(selectedOrders.get(i))); 
    } 

    CommandItemForSellerAdapter aa = new CommandItemForSellerAdapter(getActivity(), R.layout.pending_listview_item, orders); 


    ListView lv = (ListView) view.findViewById(R.id.commandListView); 
    lv.setAdapter(aa); 


    return view; 
} 

盡你所能 請參閱每個片段從Firebase數據庫調用內容,以保持異步。

我的問題是:

當我嘗試加載「同步」數據(我在我的代碼previsouly寫),列表內容由onCreate方法在最初的創造使每個片段設置爲每個標籤獲取一些內容。但是,第二個選項卡永遠不會刷新新數據。 因此,在異步情況下,onCreate方法不會返回任何數據(由於加載時間),並且新數據應該由onCreateView(類似於刷新)添加,但對於第二個選項卡它永遠不會發生!

許多小時調試之後,我只是發現了以下:

。當切換從標籤1向標籤2片段呈現爲片3。當我從標籤3切換到到標籤2時,片段呈現標籤1。即使getItem(position)返回標籤的正確位置,標籤2現在也不會調用onCreateView方法並保持爲空。

請告訴我爲什麼這個projet的行爲如此,我不想放棄,但我真的不明白這裏有什麼問題。

如果您需要更具體的信息,告訴我我可以給你任何你想要的東西。

回答

0

當使用FragmentPagerAdapter時,ViewPager會使相鄰頁面保持「活躍」狀態(左邊一個,右邊一個) - 意味着當你只有三個片段時,第二個永遠不會被銷燬。如果要在分段進入視圖時刷新數據,則必須找到其他方法 - 一個想法是使用ViewPager.addOnPageChangeListener方法添加用於頁面更改的偵聽器 - https://developer.android.com/reference/android/support/v4/view/ViewPager.html#addOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener) 然後,您可以從onPageSelected回調內觸發刷新。

就你而言,我認爲最簡單的解決方案是讓SectionsPagerAdapter實現ViewPager.OnPageChangeListener,存儲每個創建的Fragment的引用(最好是WeakReference),然後在適當的SellerFragment實例上調用一些刷新方法。

+0

好的,謝謝你,在我的情況下,我已經選擇添加一個選項卡。一點點容易哈哈 –

+0

@ pablo432我試圖在ViewPagerAdpater(這裏sectionsAdapter)添加onPageChangeListener。但我沒有取得成功。這在生命週期中從未被調用過。你能幫我嗎? –

+0

@malavshah分享一些代碼,然後我會看看:) – pablo432

相關問題