有人可以幫助我理解爲什麼下面的代碼能夠在一個片段上工作,而不是在另一個片段上工作,使得我得到兩倍於我應該具有的內部片段, TabLayout和ViewPager不同步:ViewPager具有它應該有的兩倍多的片段
片段:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.fragment_companies_ranking, container, false);
pagerAdapter = new MyPagerAdapter(getFragmentManager());
tabLayout = (TabLayout)mainView.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("1");
tabLayout.addTab(tabLayout.newTab().setText("2"));
tabLayout.addTab(tabLayout.newTab().setText("3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager)mainView.findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.requestFocus();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return mainView;
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@android:color/white"
tools:context=".activities.companies.MyFragment">
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
app:tabMode="fixed"
android:background="@color/color_white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top" />
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_below="@id/tab_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
PagerAdapter:
public class MyPageAdapter extends FragmentStatePagerAdapter {
private ArrayList<Fragment> fragments = new ArrayList<>(2);
public MyPageAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
fragments.clear();
fragments.add(OneFragment.newInstance());
fragments.add(TwoFragment.newInstance());
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
}
更新:
好了,找到了,我已經從那裏片斷被實例化在MainActivity一些吃剩的代碼,並有我添加包含ViewPager非常相同的片段。
不太清楚爲什麼它的行爲是這樣的,因爲兩個ViewPage都在不同的地方並且名稱不同,但是,這仍然是導致奇怪情況的原因。
有沒有人知道爲什麼這種情況發生時,兩個實例在技術上不同並且不應該互相影響?
或者我錯過了什麼?無論哪種方式,我感謝大家的想法,讓我重新審視所有使用過的碎片的所有內容,而沒有我可能會在這個困惑循環中迷失幾個小時。