TabLayout中的Android片段如何读取自己的索引?

时间:2017-06-01 16:23:43

标签: android android-fragments android-tablayout

如果我想显示"页码"对于每个选项卡式片段,片段如何在TabLayout中告知其自己的索引(与返回当前所选选项卡索引的tabLayout.getSelectedTabPosition()相反)?

1 个答案:

答案 0 :(得分:1)

创建片段

时可以实现这一点
public static MyFragment newInstance(int index) {
    MyFragment fragment = new MyFragment();
    Bundle bundle = new Bundle();
    bundle.putInteger("index", index);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    int index = getArguments().getInteger("index", 0);
}

在适配器中,传递位置

@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 MyFragment.newInstance(position + 1);
}