1,xml资源文件:activity_guide.xml
<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.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
2,在Java代码中使用
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class GuideActivity extends Activity {
/**
* 引导页存放图片的ViewPager
*/
private ViewPager mViewPager;
/**
* ViewPager的适配器
*/
private MyPagerAdapter adapter;
/**
* 存放图片的List集合
*/
private ArrayList<View> viewsList;
/**
* 使用ImageView动态获取图片资源
*/
private ImageView imageView1,imageView2,imageView3,imageView4;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guide);
initView();
initData();
}
/**
* 初始化数据
*/
private void initData() {
// TODO Auto-generated method stub
imageView1.setBackgroundResource(R.drawable.welcome_1);
imageView2.setBackgroundResource(R.drawable.welcome_2);
imageView3.setBackgroundResource(R.drawable.welcome_3);
imageView4.setBackgroundResource(R.drawable.welcome_4);
viewsList.add(imageView1);
viewsList.add(imageView2);
viewsList.add(imageView3);
viewsList.add(imageView4);
// 给ViewPager设置适配器
mViewPager.setAdapter(adapter);
}
/**
* 初始化控件
*/
private void initView() {
// TODO Auto-generated method stub
mViewPager = (ViewPager) findViewById(R.id.viewPager);
viewsList = new ArrayList<View>();
adapter = new MyPagerAdapter();
imageView1 = new ImageView(this);
imageView2 = new ImageView(this);
imageView3 = new ImageView(this);
imageView4 = new ImageView(this);
}
/**
* ViewPager的适配器
*
* @author Administrator
*
*/
class MyPagerAdapter extends PagerAdapter {
/**
* ViewPager每次刷新时候调用
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
container.addView(viewsList.get(position));
return viewsList.get(position);
}
/**
* ViewPager条目摧毁时调用
*/
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
container.removeView(viewsList.get(position));
}
/**
* 获取ViewPager条目个数
*/
@Override
public int getCount() {
// TODO Auto-generated method stub
return viewsList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == object;
}
}
}