使用ViewPager 实现引导页
首先定义一个Acitivyt 加载一个ViewPager控件:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2015/5/21.
*/
public class Guide extends Activity implements ViewPager.OnPageChangeListener{
private ViewPager vp;
private ViewPagerAdapter vpAdapter;
private List<View> views;
private ImageView dots[];
private int[] ids= {R.id.iv1,R.id.iv2,R.id.iv3,R.id.iv4};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.guide);
initViews();
initDots();
}
private void initDots(){
dots = new ImageView[views.size()];
for(int i=0;i<views.size();i++){
dots[i] = (ImageView) findViewById(ids[i]);
}
}
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));
views.add(inflater.inflate(R.layout.four,null));
vp = (ViewPager) findViewById(R.id.viewpager);
vpAdapter = new ViewPagerAdapter(views,this);
vp.setAdapter(vpAdapter);
vp.setOnPageChangeListener(this);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for (int i=0;i<ids.length;i++){
if(i == position){//选中当前点
dots[i].setImageResource(R.drawable.dark_dot);
}else{
dots[i].setImageResource(R.drawable.white_dot );
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
同时需要自定义一个Adapter :
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* Created by Administrator on 2015/5/21.
*/
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) {
container.removeView(views.get(position));
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
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);
}
}