如何创建标签&他们的相关碎片动态?

时间:2017-08-16 06:00:38

标签: android rest android-fragments dynamic tabs

我想使用n s 动态创建Rest API多个标签,因为每个标签在刷卡时都与Fragment相关联,我可以使用JSON(Rest API)中给出的选项卡数量动态创建选项卡+ Fragment,或者我必须单独创建所有选项卡?

enter image description here

1 个答案:

答案 0 :(得分:1)

是的,你可以:

 <android.support.design.widget.TabLayout
                android:id="@+id/htab_tabs"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_gravity="bottom"
                android:background="@color/colorDivider"
                app:tabIndicatorColor="@android:color/white" />

 <android.support.v4.view.ViewPager
        android:id="@+id/htab_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private TabLayout tabLayout;

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

        viewPager = (ViewPager) findViewById(R.id.htab_viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        //jsonResArray get from web service
        for (int i = 0; i < jsonResArray.size(); i++) {
            adapter.addFrag(new NewFragment(jsonResArray.get(i)), jsonResArray.get(i).getName());
        }
        viewPager.setAdapter(adapter);
    }

    static class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List < Fragment > mFragmentList = new ArrayList < >();
        private final List < String > mFragmentTitleList = new ArrayList < >();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}