ViewPager(Android3.0以后发布)
1、这个控件支持页面的左右滑动。
2、ViewPager是V4包的,在使用的时候需要导入V4包。
3、Viewpager不是一个单一的控件,而是一个容器。不可以直接添加View,需要使用适配器来完成相应的操作。常用的适配器有PageAdapter,FragmentPageAdapter。
4、ViewPager的应用:
1>:写布局文件
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout
3. xmlns:android="http://schemas.android.com/apk/res/android"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent">
7. <android.support.v4.view.ViewPager
8. android:id="@+id/mViewPager"
9. android:layout_width="match_parent"
10. android:layout_height="match_parent">
11. </android.support.v4.view.ViewPager>
12. </RelativeLayout>
2>:找到控件
1. mViewPager= (ViewPager) findViewById(R.id.mViewPager);
3>:获取数存放到List集合中
1. img_01 = (ImageView) findViewById(R.id.img_01);
2. img_02 = (ImageView) findViewById(R.id.img_02);
3. img_03 = (ImageView) findViewById(R.id.img_03);
4. img_04 = (ImageView) findViewById(R.id.img_04);
5.
6. lists.add(img_01);
7. lists.add(img_02);
8. lists.add(img_03);
9. lists.add(img_04);
4>:自定义适配器,实现PagerAdapter
1. /**
2. * PagerAdapter适配器
3. */
4. public class MyAdapter extends PagerAdapter{
5.
6. @Override
7. public int getCount() {//返回的是内容的条目
8. return lists.size();
9. }
10.
11. @Override
12. public boolean isViewFromObject(View view, Object object) {//view的来源是否是object
13. return view==object;
14. }
15.
16. @Override
17. public Object instantiateItem(ViewGroup container, int position) {
18. View view = lists.get(position);
19. if (view.getParent()!=null){
20. ViewGroup vg = (ViewGroup) view.getParent();
21. vg.removeView(view);
22. }
23. container.removeView(view);
24. container.addView(view);
25. return view;
26. }
27.
28. @Override
29. public void destroyItem(ViewGroup container, int position, Object object) {
30. container.removeView(lists.get(position));
31. }
32. }
5>:给ViewPager对象绑定适配器
1. mViewPager.setAdapter(mMyAdapter);
6>:实现ViewPager自动播放
1. new Thread(new Runnable() {
2. @Override
3. public void run() {
4. try {
5. while (true){
6. Thread.sleep(3000);
7. if(++positionIndex>3){
8. positionIndex=0;
9. }
10. Handler.sendEmptyMessage(100);
11. }
12. } catch (InterruptedException e) {
13. e.printStackTrace();
14. }
15. }
16. }).start();
1. Handler Handler=new Handler(){
2. @Override
3. public void handleMessage(Message msg) {
4. switch (msg.what){
5. case 100:
6. mViewPager.setCurrentItem(positionIndex);
7. break;
8. }
9. }
10. };
5、ViewPager的应用二(实现上述应用的无限循环滑动,主要的区别在于自定义适配器)
1>:写布局文件
2>:找到控件
3>:获取数存放到List集合中
4>:自定义适配器,实现PagerAdapter
5>:给ViewPager对象绑定适配器
1. /**
2. * PagerAdapter适配器
3. */
4. public class MyAdapter extends PagerAdapter{
5.
6. //将容器设置为最大值(理论上是可以滑动完成的)
7. @Override
8. public int getCount() {//返回的是内容的条目
9. return Integer.MAX_VALUE;
10. }
11.
12. @Override
13. public boolean isViewFromObject(View view, Object object) {//view的来源是否是object
14. return view==object;
15. }
16.
17. @Override
18. public Object instantiateItem(ViewGroup container, int position) {
19. View view = lists.get(position % lists.size());
20. if (view.getParent()!=null){
21. ViewGroup vg = (ViewGroup) view.getParent();
22. vg.removeView(view);
23. }
24. container.removeView(view);
25. container.addView(view);
26. return view;
27. }
28.
29. @Override
30. public void destroyItem(ViewGroup container, int position, Object object) {
31. container.removeView(lists.get(position % lists.size()));
32. }
33. }
6>:实现ViewPager自动播放
1. Handler mHandler=new Handler(){
2. @Override
3. public void handleMessage(Message msg) {
4. switch (msg.what){
5. case 100:
6. mViewPager.setCurrentItem(mIndex++);
7. break;
8. }
9. }
10. };
1. new Thread(new Runnable() {
2. @Override
3. public void run() {
4.
5. try {
6. while (true){
7. Thread.sleep(3000);
8. Message msg=new Message();
9. msg.what=100;
10. mHandler.sendMessage(msg);
11. }
12. } catch (InterruptedException e) {
13. e.printStackTrace();
14. }
15. }
16. }).start();
6、广告条制作
1>:写布局文件
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. tools:context="com.example.tingxiangxi.viewpagerapplication.Main3Activity">
7.
8. <LinearLayout
9. android:orientation="vertical"
10. android:layout_width="match_parent"
11. android:layout_height="300dp">
12.
13. <android.support.v4.view.ViewPager
14. android:id="@+id/mViewpager"
15. android:layout_width="match_parent"
16. android:layout_height="260dp">
17.
18. </android.support.v4.view.ViewPager>
19.
20. <LinearLayout
21. android:layout_width="match_parent"
22. android:layout_height="40dp"
23. android:layout_below="@+id/mViewpager"
24. android:layout_alignParentBottom="true"
25. android:background="#ccc"
26. android:gravity="center"
27. android:orientation="vertical">
28.
29. <TextView
30. android:id="@+id/tv_title"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:text="标题"
34. android:textSize="16sp" />
35.
36. <LinearLayout
37. android:id="@+id/selectedContainer"
38. android:layout_width="wrap_content"
39. android:layout_height="wrap_content"
40. android:orientation="horizontal">
41.
42. </LinearLayout>
43. </LinearLayout>
44. </LinearLayout>
45. <!--下面还可能有内容-->
46. </RelativeLayout>
2>:查找控件
1. /**
2. * 查找控件
3. */
4. private void findView(){
5. mViewPager = (ViewPager) findViewById(R.id.mViewpager);
6. title=(TextView) findViewById(R.id.tv_title);
7. selectedContainer=(LinearLayout) findViewById(R.id.selectedContainer);
8. }
3>:初始化数据
1. /**
2. * 初始化数据
3. */
4. private void initData(){
5. for (int i = 0; i <titles.length; i++) {
6. ImageView img=new ImageView(Main3Activity.this);
7. img.setBackgroundResource(immgs[i]);
8. img.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
9. //将要显示的View装到容器中
10. lists.add(img);
11. //初始化“点”的view
12. View view=new View(Main3Activity.this);
13. //给“点”设置背景
14. view.setBackgroundResource(R.drawable.dot_normal);
15. LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(25,25);
16. //给“点”设置左右上下的外边距
17. params.setMargins(20,5,0,0);
18. view.setLayoutParams(params);
19. //将“点”添加到容器中去
20. selectedContainer.addView(view);
21. //把动态生成的点保存到集合中
22. points.add(view);
23.
24. }
25. //设置默认标题
26. title.setText(titles[0]);
27. //将“点”变成红色
28. points.get(0).setBackgroundResource(R.drawable.dot_enable);
29. }
4>:自定义适配器
1. /**
2. * 自定义适配器
3. */
4. private class MyAdapter extends PagerAdapter{
5.
6. //给容器设置最大值
7. @Override
8. public int getCount() {
9. return Integer.MAX_VALUE;
10. }
11.
12. @Override
13. public boolean isViewFromObject(View view, Object object) {
14. return view==object;
15. }
16.
17. @Override
18. public Object instantiateItem(ViewGroup container, int position) {
19. View view = lists.get(position % lists.size());
20. if (view.getParent()!=null){
21. ViewGroup vg = (ViewGroup) view.getParent();
22. vg.removeView(view);
23. }
24. container.removeView(view);
25. container.addView(view);
26. return view;
27. }
28.
29. @Override
30. public void destroyItem(ViewGroup container, int position, Object object) {
31. container.removeView(lists.get(position % lists.size()));
32. }
33. }
5>:给ViewPager对象绑定适配器
1. /**
2. * 创建方法来添加适配器
3. */
4. private void setAdapter() {
5. MyAdapter mMyAdapter =new MyAdapter();
6. mViewPager.setAdapter(mMyAdapter);
7. }
6>:设置页面改变的监听事件
1. /**
2. * 设置页面改变的监听
3. */
4. private void setOnPagerListener() {
5. mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
6. @Override
7. public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
8.
9. }
10.
11. /**
12. * 某一个页面被选中
13. * @param position
14. */
15. @Override
16. public void onPageSelected(int position) {
17. //改变标题
18. title.setText(titles[position % titles.length]);
19. points.get(prePosittion).setBackgroundResource(R.drawable.dot_normal);
20. points.get(position%titles.length).setBackgroundResource(R.drawable.dot_enable);
21. //记录改变之前的位置
22. prePosittion=position%titles.length;
23. }
24.
25. @Override
26. public void onPageScrollStateChanged(int state) {
27.
28. }
29. });
30. }
7、实现广告的自动循环
1. /**
2. * 自动滑动
3. */
4. private void autoFling() {
5. new Thread(new Runnable() {
6. @Override
7. public void run() {
8. while (isLooping){
9. try {
10. Thread.sleep(3000);
11. mHandler.sendEmptyMessage(100);
12.
13. } catch (InterruptedException e) {
14. e.printStackTrace();
15. }
16. }
17. }
18. }).start();
19. }
20.
21. Handler mHandler=new Handler(){
22. @Override
23. public void handleMessage(Message msg) {
24. switch (msg.what){
25. case 100:
26. //获取当前位置
27. int position = mViewPager.getCurrentItem();
28. //向下一个页面进行滑动
29. mViewPager.setCurrentItem(position+1);
30. break;
31. }
32. }
33. };
7、Fragment与ViewPager的混合使用
1>:写布局文件
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. tools:context="com.example.tingxiangxi.viewpagerapplication.Main4Activity">
7.
8. <android.support.v4.view.ViewPager
9. android:id="@+id/mViewpager"
10. android:layout_width="match_parent"
11. android:layout_height="match_parent">
12.
13. </android.support.v4.view.ViewPager>
14.
15. </RelativeLayout>
2>:查找控件
1. mViewPager = (ViewPager) findViewById(R.id.mViewpager);
3>:初始化数据
1. /**
2. * 初始化数据
3. */
4. private void initData() {
5. for (int i = 0; i < 4; i++) {
6. ContentFragment contentFragment=new ContentFragment();
7. Bundle bundle = new Bundle();
8. bundle.putString("content","页面"+i);
9. contentFragment.setArguments(bundle);
10. lists.add(contentFragment);
11. }
12. }
4>:自定义适配器
1. /**
2. * 自定义适配器
3. * 这个适配器是Viewpager专门设置给Fragment的
4. */
5. private class MyAdapter extends FragmentPagerAdapter{
6.
7. public MyAdapter(FragmentManager fm) {
8. super(fm);
9. }
10.
11. @Override
12. public android.support.v4.app.Fragment getItem(int position) {
13. return lists.get(position);
14. }
15.
16. @Override
17. public int getCount() {
18. return lists.size();
19. }
20. }
21. }
5>:将ViewPager对象绑定适配器
1. /**
2. * 设置适配器
3. */
4. private void setAdapter() {
5. MyAdapter myAdapter=new MyAdapter(getSupportFragmentManager());
6. mViewPager.setAdapter(myAdapter);
7. }
6>:Fragment中的代码如下
1. import android.os.Bundle;
2. import android.support.v4.app.Fragment;
3. import android.view.LayoutInflater;
4. import android.view.View;
5. import android.view.ViewGroup;
6. import android.widget.TextView;
7.
8. public class ContentFragment extends Fragment {
9.
10. private TextView tv_01;
11.
12. @Override
13. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
14. View view=inflater.inflate(R.layout.activity_content_fragment,null,false);
15. findView(view);
16. return view;
17. }
18.
19. private void findView(View view) {
20. tv_01 = (TextView) view.findViewById(R.id.tv_01);
21. }
22.
23. @Override
24. public void onActivityCreated(Bundle savedInstanceState) {
25. super.onActivityCreated(savedInstanceState);
26. String result = getArguments().getString("content");
27. tv_01.setText(result);
28. }
29. }
8、综合案例
1>:写布局文件
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:orientation="vertical"
7. tools:context="com.example.tingxiangxi.viewpagerapplication.Main5Activity">
8.
9. <HorizontalScrollView
10. android:id="@+id/hsv"
11. android:layout_width="match_parent"
12. android:layout_height="50dp"
13. android:fillViewport="false"
14. android:scrollbars="none"
15. >
16.
17. <LinearLayout
18. android:layout_width="match_parent"
19. android:layout_height="50dp"
20. android:orientation="vertical">
21.
22. <LinearLayout
23. android:id="@+id/titleContainer"
24. android:layout_width="wrap_content"
25. android:layout_height="45dp"
26. android:gravity="center"
27. android:orientation="horizontal">
28. </LinearLayout>
29. <TextView
30. android:id="@+id/fling"
31. android:layout_width="0dp"
32. android:layout_height="2dp"
33. android:background="#3A94FF"></TextView>
34.
35. <TextView
36. android:layout_width="match_parent"
37. android:layout_height="1dp"
38. android:background="#3A94FF"></TextView>
39.
40.
41. </LinearLayout>
42. </HorizontalScrollView>
43.
44. <android.support.v4.view.ViewPager
45. android:id="@+id/mViewpager"
46. android:layout_width="match_parent"
47. android:layout_height="match_parent">
48.
49. </android.support.v4.view.ViewPager>
50. </LinearLayout>
2>:查找控件
1. /**
2. * 查找控件
3. */
4. private void findView() {
5. mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
6. mViewPager=(ViewPager) findViewById(R.id.mViewpager);
7. titleContainer=(LinearLayout) findViewById(R.id.titleContainer);
8. fling=findViewById(R.id.fling);
9. }
3>:初始化数据
1. /**
2. * 初始化数据
3. */
4. private void initData() {
5. initScreenWidth();
6. for (int i = 0; i < titles.length; i++) {
7. TextView mTextView=new TextView(Main5Activity.this);
8. mTextView.setTextSize(20);
9. mTextView.setGravity(Gravity.CENTER);
10. mTextView.setText(titles[i]);
11. mTextView.setLayoutParams(new LinearLayout.LayoutParams(mScreenWidth/3,LinearLayout.LayoutParams.WRAP_CONTENT));
12. titleContainer.addView(mTextView);
13. textViews.add(mTextView);
14.
15. //初始化Fragment
16. ContentFragment contentFragment=new ContentFragment();
17. Bundle bundle = new Bundle();
18. bundle.putString("content",titles[1]);
19. contentFragment.setArguments(bundle);
20. fragments.add(contentFragment);
21.
22. }
23. setViewFlingWidth();
24. setAdapter();
25. setTitleTabListener();
26. setPagerListener();
27. }
4>:自定义适配器
1. /**
2. * 自定义适配器
3. */
4. private class MyAdapter extends FragmentPagerAdapter{
5.
6. public MyAdapter(FragmentManager fm) {
7. super(fm);
8. }
9.
10. @Override
11. public Fragment getItem(int position) {
12. return fragments.get(position);
13. }
14.
15. @Override
16. public int getCount() {
17. return titles.length;
18. }
19. }
5>:将ViewPager对象绑定适配器
1. /**
2. * 设置适配器
3. */
4. private void setAdapter() {
5. MyAdapter mMyAdapter=new MyAdapter(getSupportFragmentManager());
6. mViewPager.setAdapter(mMyAdapter);
7. }
6>:设置切换卡的TextView的监听
1. /**
2. * 设置切换卡的监听事件
3. */
4. private void setTitleTabListener() {
5. int childCount = titleContainer.getChildCount();
6. for (int i = 0; i < childCount; i++) {
7. titleContainer.getChildAt(i).setTag(i);
8. titleContainer.getChildAt(i).setOnClickListener(new Listener());
9. }
10. }
11.
12. /**
13. * titleTextView的监听事件
14. */
15. private class Listener implements View.OnClickListener{
16.
17. @Override
18. public void onClick(View v) {
19. mViewPager.setCurrentItem((int)v.getTag());
20. }
21. }
7>:设置滑块的宽度
1. /**
2. * 获取屏幕宽度
3. */
4. private void initScreenWidth() {
5. DisplayMetrics mDisplayMetrics=new DisplayMetrics();
6. getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
7. mScreenWidth=mDisplayMetrics.widthPixels;
8. }
1. /**
2. * 设置滑动块的宽度
3. */
4. private void setViewFlingWidth() {
5. params=new LinearLayout.LayoutParams(mScreenWidth/3,fling.getLayoutParams().height);
6. fling.setLayoutParams(params);
7. }
8>:设置页面滚动的监听事件
1. /**
2. * 滑动的时候mHorizontalScrollView跟着滑动
3. * @param position
4. */
5. private void setSooth(int position) {
6. int offset=titleContainer.getChildAt(position).getLeft()-mScreenWidth/2+titleContainer.getChildAt(position).getWidth()/2;
7. mHorizontalScrollView.smoothScrollTo(offset,0);
8. }
1. /**
2. * 设置页面滚动的监听事件
3. */
4. private void setPagerListener() {
5. mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
6. /**
7. *
8. * @param position 滚动的位置
9. * @param positionOffset 偏移量
10. * @param positionOffsetPixels 偏移的像素
11. */
12. @Override
13. public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
14. params.leftMargin= (int) ((position+positionOffset)*params.width);
15. fling.setLayoutParams(params);
16. }
17.
18. @Override
19. public void onPageSelected(int position) {
20. textViews.get(prePosition).setTextColor(Color.BLACK);
21. textViews.get(position).setTextColor(Color.RED);
22. prePosition=position;
23. setSooth(position);
24. }
25.
26.
27.
28. @Override
29. public void onPageScrollStateChanged(int state) {
30.
31. }
32. });
33. }
共同学习,写下你的评论
评论加载中...
作者其他优质文章