Android之Tablayout和ViewPager和Fragment的使用
- 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>
- 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;
}
}