您的位置:首页 > 其它

PagerSlidingTabStrip开源库实现ViewPager界面

2016-07-18 09:01 344 查看
PagerSlidingTabStrip的github地址

在布局文件中添加

<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"/>
<com.astuetz.PagerSlidingTabStrip
android:id="@+id/tabstrip"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#f000"
app:pstsShouldExpand="true"
app:pstsIndicatorColor="#ff00cd79"
app:pstsIndicatorHeight="4dp" />


将ViewPager和PgerSlidingTabStrip放在主界面中

然后新建一个布局文件pager_fragment.xml,将ViewPager的每一页设置为碎片。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.doubandemo.PagerFrament">
<TextView
android:id="@+id/tv_frament"
android:textSize="100dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>


再新建PagerFragment类继承Fragment,重写onCreateView()方法用来加载布局文件

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//加载碎片布局
View view = inflater.inflate(R.layout.pager_frament,container,false);
TextView tv = (TextView) view.findViewById(R.id.tv_frament);
//取出MainActivity传递来的参数
Bundle bundle = getArguments();
//根据键取出对应的值
int num = bundle.getInt("fram_text");
//设置textview
tv.setText(""+num);
return view;
}


在MainActivity中为ViewPager添加数据

viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));

//新建内部类继承FragmentPagerAdapter
private class MyAdapter extends FragmentPagerAdapter {
//重写构造方法
public MyAdapter(FragmentManager fm) {
super(fm);
}
//加载position索引下的Fragment布局
@Override
public Fragment getItem(int position) {
Fragment fragment;
//加载碎片,并将页码通过bundle传递
Bundle bundle = new Bundle();
fragment = new PagerFrament();
bundle.putInt("fram_text",position);
fragment.setArguments(bundle);
return fragment;
}
//获取滑动页面的个数
@Override
public int getCount() {
return titleList.size();
}
//设置每个页面的标题
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}

//为pagerslidingtabStrip指定ViewPager
pagerslidingtabStrip.setViewPager(viewPager);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: