接着上一篇博客,上一篇博客是用ImageSwitcher实现用户向导功能,现在用ViewPager实现相同的功能。直接看代码:
布局文件activity_main.xml
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity"> <android.support.v4.view.viewpager android:id="@+id/viewpager" android:layout_width="fill_parent" android:layout_height="fill_parent"></android.support.v4.view.viewpager> <linearlayout android:id="@+id/dots" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_marginbottom="50dp" android:gravity="center_horizontal" android:orientation="horizontal"> </linearlayout></relativelayout>
ViewPager页面的切换用小圆点来表示当前是第几页,这里使用drawable.xml文件去绘制的,如下:
dot_focus.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <corners android:radius="5dip"></corners> <solid android:color="#FF930000"></solid></shape>dot_nomal.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <corners android:radius="5dip"></corners> <solid android:color="#FF3C3C3C"></solid></shape>在Activity中如下代码:
package com.example.viewpagerautoswitch;import java.util.ArrayList;import java.util.List;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup.LayoutParams;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;@SuppressLint("HandlerLeak")public class MainActivity extends Activity { private ViewPager mViewPager ; private MyPagerAdapter mViewPagerAdapter ; private LinearLayout mLinearLayout ; private ImageView[] mImageDots ; private Context mContext ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = MainActivity.this ; mViewPager = (ViewPager)findViewById(R.id.viewpager); mLinearLayout = (LinearLayout)findViewById(R.id.dots); initViewPager(getImageItem() ,0); } public void initViewPager(List<imageview> mList ,int position){ mImageDots = new ImageView[mList.size()]; for(int i=0 ;i<mlist.size imageview image="new" image.setlayoutparams layoutparams image.setbackgroundresource mimagedots mlinearlayout.addview textview tv="new" tv.setlayoutparams mviewpageradapter="new" mypageradapter mviewpager.setonpagechangelistener onpagechangelistener onpagescrollstatechanged> onPageSelected --> onPageScrolled -->onPageScrollStateChanged @Override public void onPageSelected(int position) { for(int i=0 ;i<mimagedots.length if position mimagedots public void onpagescrolled current_position float persent int px onpagescrollstatechanged state mviewpager.setonclicklistener onclicklistener onclick view mviewpager.setadapter mviewpager.setcurrentitem list> getImageItem(){ List<imageview> list = new ArrayList<imageview>(); ImageView img = new ImageView(mContext); img.setBackgroundResource(R.drawable.img1); list.add(img); img = new ImageView(mContext); img.setBackgroundResource(R.drawable.img2); list.add(img); img = new ImageView(mContext); img.setBackgroundResource(R.drawable.img3); list.add(img); return list ; } @Override public void finish() { super.finish(); }}</imageview></imageview></mimagedots.length></mlist.size></imageview>这里ViewPager和ImageSwitcher不同的地方在于ViewPager是用Adapter去封装需要加装的页面,而ImageSwitcher使用ViewFactory去加装图片的。所以使用viewPager时需要集成PagerAdapter实现相应的接口即可。如下:
MyPagerAdapter.java
package com.example.viewpagerautoswitch;import java.util.List;import android.content.Context;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 MyPagerAdapter extends PagerAdapter { private List<imageview> items ; private Context mContext ; public MyPagerAdapter(Context context,List<imageview> item){ mContext = context ; items = item ; } @Override public int getCount() { return items == null ? 0 : items.size(); } @Override public boolean isViewFromObject(View view, Object obj) { return view == (View)obj; } @Override public Object instantiateItem (ViewGroup container, int position) { ImageView image = items.get(position); ((ViewPager)container).addView(image, 0); return image; } @Override public void destroyItem (ViewGroup container, int position, Object object) { container.removeView((View)object); } }</imageview></imageview>这样就可以实现用户向导的功能了,具体的页面效果如下:图片显示的是第二张pager的情况,这个是android手机上的demo,如果是Android机顶盒上使用的话,可以捕捉左右键去时间滑动。
有时候,在应用中不仅仅是为了可以切换图片,或许这个Pager他有点击事件所表示的意思,比如点击之后跳转到某个网页,这么办!? 这里可以封装你的Adapter数据,将ImageView,替换成你定义的封装数据,在Adapter中重写的instantiateItem()中去实例化一个View,然后返回即可,由于初始化Adapter的list在MainActivity中有原始数据,那么当用户在点击某个pager时,提取这个Pager所表示的信息,比如一个网址链接等。
其实,现在好多app中使用了自动循环切换的效果,这个效果不外乎就是用计时器+Handler实现,只需要添加如下代码即可:
private Timer mTimer ; private void startTimer(){ if(mTimer == null){ mTimer = new Timer(true); } mTimer.schedule(new TimerTask(){ @Override public void run() { mHandler.sendEmptyMessage(0); } }, 1000, 4000) ;// 延迟1秒开始执行,循环执行时间是4秒 } private void stopTimer(){ if(mTimer != null){ mTimer.cancel() ; mTimer = null ; } } @SuppressLint("HandlerLeak") Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { if(msg.what == 0){ int mViewPagerCurrentIndex = mViewPager.getCurrentItem(); mViewPagerCurrentIndex = (++mViewPagerCurrentIndex) % mViewPager.getAdapter().getCount() ; mViewPager.setCurrentItem(mViewPagerCurrentIndex, true); } }; };这段代码中提供了开始和停止自动循环切换的开关startTimer()、stopTimer(),通过这两个方法,可以更具需求对ViewPager是否需要自动切换做操作。
此外,ImageSwitcher的自动切换同样可以使用此代码去控制。