Android之Tablayout和ViewPager和Fragment的使用

Android之Tablayout和ViewPager和Fragment的使用

  1. xml:
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="45dp"></android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></android.support.v4.view.ViewPager>

  1. java:
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private ArrayList<String> titleDatas = new ArrayList<>();
    private ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();


	viewPager = findViewById(R.id.viewPager);
    tabLayout = findViewById(R.id.tabLayout);
    titleDatas.add("页面1");
    titleDatas.add("页面2");
	fragmentList.add(new MyFragment().newInstance());
	fragmentList.add(new MyFragment().newInstance());
    MyViewPageAdapter myViewPageAdapter = new MyViewPageAdapter(getSupportFragmentManager(), titleDatas, fragmentList);
    viewPager.setAdapter(myViewPageAdapter);
    tabLayout.setupWithViewPager(viewPager);                            
	tabLayout.setTabsFromPagerAdapter(myViewPageAdapter);


	public class MyViewPageAdapter extends FragmentPagerAdapter {
        private ArrayList<String> titleList;
        private ArrayList<IndicatorsCareFragment> fragmentList;

        public MyViewPageAdapter(FragmentManager fm, ArrayList<String> titleList, ArrayList<IndicatorsCareFragment> fragmentList) {
            super(fm);
            this.titleList = titleList;
            this.fragmentList = fragmentList;
        }

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

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

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

MyFragment:

public class IndicatorsCareFragment extends Fragment {
    private List<RssData> data = new ArrayList<>();
    private Rsslist rsslist;
    private int isDay;
    AddIndicatorsCareActivity activity;

    private RecyclerView rv_list;

    public static IndicatorsCareFragment newInstance() {
        IndicatorsCareFragment f = new IndicatorsCareFragment();
        return f;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_expandable_listview, container, false);
        return view;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值