Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> Android App中用Handler實現ViewPager頁面的自動切換

Android App中用Handler實現ViewPager頁面的自動切換

編輯:Android開發實例

在很多電商網頁及app上都有自動切換的商品的推廣快,感覺體驗挺不錯的,正好今天學習使用ViewPager,因此也實現了一個功能類似的demo。

下面是其中的兩個截圖:

實現一個自動播放功能的ViewPager,要做的主要有以下的幾個部分:

實現一個ViewPagerAdapter,用於為ViewPager提供展示內容(例如上面的兩張小貓圖片)

 public class ViewPagerAdapter extends PagerAdapter {
    private List<View> mData;
    public ViewPagerAdapter(List<View> mData) {
      this.mData = mData;
    }

    @Override
    public int getCount() {
      return mData.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == arg1;
    }
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      View v = mData.get(position);
      container.addView(v);
      return v;
    }
    
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//  super.destroyItem(container, position, object);
      container.removeView(mData.get(position));
    }
    
  }

實現一個OnPageChangeListener,這樣在頁面切換後可以提示當前頁面所在的位置(例如上圖中,左下角的3個圓點,紅色表示當前頁面)

 private class ViewPageChangeListener implements OnPageChangeListener {

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    //監聽頁面改變事件來改變viewIndicator中的指示圖片
    @Override
    public void onPageSelected(int arg0) {
      int len = viewIndicator.getChildCount();
      for(int i = 0; i < len; ++i)
        viewIndicator.getChildAt(i).setBackgroundResource(R.drawable.tip_normal);
      viewIndicator.getChildAt(arg0).setBackgroundResource(R.drawable.tip_select);
    }
    
  }

實現一個Handler,用於在一定的時間間隔後修改UI(將當前顯示的圖片切換到下一個)

private Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
      switch(msg.what) {
      case 1:
        int totalcount = pagers.size();//autoChangeViewPager.getChildCount();
        int currentItem = autoChangeViewPager.getCurrentItem();
        
        int toItem = currentItem + 1 == totalcount ? 0 : currentItem + 1;
        
        Log.i(TAG, "totalcount: " + totalcount + "  currentItem: " + currentItem + "  toItem: " + toItem);
        
        autoChangeViewPager.setCurrentItem(toItem, true);
        
        //每兩秒鐘發送一個message,用於切換viewPager中的圖片
        this.sendEmptyMessageDelayed(1, 2000);
      }
    }
  };

上面這3段就是主要的代碼,除此之外,還需要在onResume()中發送一個起始message以及在onStop()中停止ViewPager頁面的自動切換等內容。
完整的代碼如下:

public class MainActivity extends Activity {
  private static final String TAG = MainActivity.class.getSimpleName();
  private ViewPager autoChangeViewPager;
  
  //用來指示當前顯示圖片所在位置
  private LinearLayout viewIndicator;
  
  //包含要在ViewPager中顯示的圖片
  private List<View> pagers;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    autoChangeViewPager = (ViewPager) findViewById(R.id.autoVP);
    viewIndicator = (LinearLayout) findViewById(R.id.vpindicator);
    
    initAdapter();
    
    //監聽頁面改變事件來改變viewIndicator中的指示圖片
    autoChangeViewPager.setOnPageChangeListener(new ViewPageChangeListener());
    
  }
  
  private void initAdapter() {
    //即將在viewPager中展示的圖片資源
    int[] imgs = {R.drawable.i1, R.drawable.i2, R.drawable.i3};
    
    //init pagers;
    pagers = new ArrayList<View>();
    LinearLayout.LayoutParams img_params = new LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT
        );
    for(int i = 0; i < imgs.length; ++i) {
      ImageView iv = new ImageView(this);
      iv.setBackgroundResource(imgs[i]);
      iv.setLayoutParams(img_params);
      final int index = i;
      iv.setOnClickListener(new OnClickListener() {
        //當viewPager中的圖片被點擊後,跳轉到新的activity
        @Override
        public void onClick(View v) {
          Intent i = new Intent(MainActivity.this, InvokedActivity.class);
          i.putExtra("name", "cat " + index);
          MainActivity.this.startActivity(i);
        }
      });
      pagers.add(iv);
    }
    autoChangeViewPager.setAdapter(new ViewPagerAdapter(pagers));
    
    //init indicator
    LinearLayout.LayoutParams ind_params = new LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
        );
    for(int i = 0; i < imgs.length; ++i) {
      ImageView iv = new ImageView(this);
      if(i == 0)
        iv.setBackgroundResource(R.drawable.tip_select);
      else
        iv.setBackgroundResource(R.drawable.tip_normal);
      iv.setLayoutParams(ind_params);
      viewIndicator.addView(iv);
    }
  }
  
  @Override
  protected void onResume() {
    super.onResume();
    //activity啟動兩秒鐘後,發送一個message,用來將viewPager中的圖片切換到下一個
    mHandler.sendEmptyMessageDelayed(1, 2000);
  }
  
  @Override
  protected void onStop() {
    super.onStop();
    //停止viewPager中圖片的自動切換
    mHandler.removeMessages(1);
  }

  public class ViewPagerAdapter extends PagerAdapter {
    private List<View> mData;
    public ViewPagerAdapter(List<View> mData) {
      this.mData = mData;
    }

    @Override
    public int getCount() {
      return mData.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == arg1;
    }
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      View v = mData.get(position);
      container.addView(v);
      return v;
    }
    
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//  super.destroyItem(container, position, object);
      container.removeView(mData.get(position));
    }
    
  }
  
  private class ViewPageChangeListener implements OnPageChangeListener {

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    //監聽頁面改變事件來改變viewIndicator中的指示圖片
    @Override
    public void onPageSelected(int arg0) {
      int len = viewIndicator.getChildCount();
      for(int i = 0; i < len; ++i)
        viewIndicator.getChildAt(i).setBackgroundResource(R.drawable.tip_normal);
      viewIndicator.getChildAt(arg0).setBackgroundResource(R.drawable.tip_select);
    }
    
  }
  
  private Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
      switch(msg.what) {
      case 1:
        int totalcount = pagers.size();//autoChangeViewPager.getChildCount();
        int currentItem = autoChangeViewPager.getCurrentItem();
        
        int toItem = currentItem + 1 == totalcount ? 0 : currentItem + 1;
        
        Log.i(TAG, "totalcount: " + totalcount + "  currentItem: " + currentItem + "  toItem: " + toItem);
        
        autoChangeViewPager.setCurrentItem(toItem, true);
        
        //每兩秒鐘發送一個message,用於切換viewPager中的圖片
        this.sendEmptyMessageDelayed(1, 2000);
      }
    }
  };
}

布局文件如下:(上面代碼中的InvokedActivity非常簡單,此處就省略了)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >

  <android.support.v4.view.ViewPager
    android:id="@+id/autoVP"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

  <LinearLayout
    android:id="@+id/vpindicator"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="horizontal" />

</FrameLayout>

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved