实现原理:使用ViewPager控件(com.android.support:support-v4:22.1.1),把引导页的layout文件放进ViewPager控件就可以了。
ViewPager控件本质上也是个列表控件,横向滚动,一个页面一个页面的滚动,底下并没有滚动条,所以非常适合做引导页,和页签的tap控件来做横向滚动的页面也非常常用。
首先引用 com.android.support:support-v4:22.1.1
引导页面的layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="demo.viewpagerdemo.GuideActivity"> <android.support.v4.view.ViewPager android:id="@+id/guide_activity_viewpager" android:layout_width="fill_parent" android:layout_height="fill_parent" > </android.support.v4.view.ViewPager> </RelativeLayout>
package demo.viewpagerdemo; import android.app.Activity; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import java.util.ArrayList; import java.util.List; public class GuideActivity extends Activity { private View mPage1, mPage2, mPage3; private List<View> mViews = new ArrayList<View>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_guide); ViewPager vp=(ViewPager)findViewById(R.id.guide_activity_viewpager); mPage1 = LayoutInflater.from(this).inflate( R.layout.guide_page1, null); mPage2 = LayoutInflater.from(this).inflate( R.layout.guide_page2, null); mPage3 = LayoutInflater.from(this).inflate( R.layout.guide_page3, null); mViews.add(mPage1); mViews.add(mPage2); mViews.add(mPage3); vp.setAdapter(new BasePagerAdapter(this, mViews)); } }
注意ViewPager需要使用PagerAdapter适配器,所以需要继承PagerAdapter类来实现一个适配器
public class BasePagerAdapter extends PagerAdapter { private Context mContext; private List<? extends View> mViews; public BasePagerAdapter(Context mContext, List<? extends View> mViews) { this.mContext = mContext; this.mViews = mViews; } @Override public int getCount() { return mViews.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mViews.get(position)); return mViews.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mViews.get(position)); } }
时间: 2024-10-15 04:50:35