Android ViewPager引导页

2017-03-10  本文已影响168人  csp

程序入口是Guide,一个三个页面的引导页,需要使用到ViewPager,Android里面PagerAdapter相当于ios里面的cell。
guide.xml中配置:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00000000"
    >

</android.support.v4.view.ViewPager>

</RelativeLayout>
在ViewPagerAdapter中重写一些方法:
public class ViewPagerAdapter extends PagerAdapter{

private List<View>views;
private Context context;

public ViewPagerAdapter(List<View>views, Context context){
    this.views = views;
    this.context = context;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//        super.destroyItem(container, position, object);

    ((ViewPager)container).removeView(views.get(position));
}

@Override
public Object instantiateItem(ViewGroup container, int position) {

    ((ViewPager)container).addView(views.get(position));

    return views.get(position);
}

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

@Override
public boolean isViewFromObject(View view, Object object) {
    return (view == object);
}

}
最后在Guide中使用:
public class Guide extends Activity {

private ViewPager vp;
private ViewPagerAdapter vpAdapter;
private List<View>views;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.guide);
    initViews();
}

private void initViews(){

    LayoutInflater inflater = LayoutInflater.from(this);

    views = new ArrayList<View>();
    views.add(inflater.inflate(R.layout.one,null));
    views.add(inflater.inflate(R.layout.two,null));
    views.add(inflater.inflate(R.layout.three,null));

    vpAdapter = new ViewPagerAdapter(views,this);
    vp = (ViewPager)findViewById(R.id.viewPager);
    vp.setAdapter(vpAdapter);

}

}

上一篇下一篇

猜你喜欢

热点阅读