Android自訂控制項實現簡單的輪播圖控制項_Android

來源:互聯網
上載者:User

最近要做一個輪播圖的效果,網上看了幾篇文章,基本上都能找到實現,效果還挺不錯,但是在寫的時候感覺每次都要單獨去重新在Activity裡寫一堆代碼。於是自己封裝了一下。本篇輪播圖實現原理原文出處:迴圈廣告位組件的實現,這裡只是做了下封裝成一個控制項,不必每次重複寫代碼了。

效果圖:

實現分析
輪播圖的功能就是實現左右滑動的廣告、圖片資訊展示,那我們就用ViewPager來實現,由於考慮到使用者體驗,我們還需要在下面加一個指標來標示滑動到了第幾張輪播圖。指標我們可以用一個線性布局來根據要展示的輪播圖設定顯示的View,我們要做這樣的一個控制項沒有什麼特殊的效果,其實就是兩個控制項的組合,只是我們要在內部處理好它們之間的互動關係(其實就是ViewPager滾動的時候,下面指標的展示),所以我們就用自訂控制項當中的組合方式來實現。
下面開始

1、定義一個控制項繼承FrameLayout,寫一個xml檔案

public class CarouselView extends FrameLayout implements ViewPager.OnPageChangeListener {  private Context context;  private int totalCount =100;//總數,這是為實現無限滑動設定的  private int showCount;//要顯示的輪播圖數量  private int currentPosition =0;//當前ViewPager的位置  private ViewPager viewPager;  private LinearLayout carouselLayout;//展示指標的布局  private Adapter adapter;  private int pageItemWidth;//每個指標的寬度  private boolean isUserTouched = false;  public CarouselView(Context context) {    super(context);    this.context = context;  }  public CarouselView(Context context, AttributeSet attrs) {    super(context, attrs);    this.context = context;  }  public CarouselView(Context context, AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);    this.context = context;  }<?xml version="1.0" encoding="utf-8"?><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/gallery"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:unselectedAlpha="1">  </android.support.v4.view.ViewPager>  <LinearLayout android:layout_height="wrap_content"    android:layout_width="fill_parent"    android:orientation="horizontal"    android:gravity="center"    android:layout_gravity="center|bottom"    android:id="@+id/CarouselLayoutPage"    android:padding="10dip">  </LinearLayout></FrameLayout>

上面的代碼把兩個要用到的控制項ViewPager和carouselLayout都包含在定義的CarouselView裡面了,下面就是要擷取

2、onFinishInflate()中擷取我們需要的控制項

@Override  protected void onFinishInflate() {    super.onFinishInflate();    View view = LayoutInflater.from(context).inflate(R.layout.carousel_layout,null);    this.viewPager = (ViewPager) view.findViewById(R.id.gallery);    this.carouselLayout = (LinearLayout)view.findViewById(R.id.CarouselLayoutPage);    pageItemWidth = ConvertUtils.dip2px(context,5);    this.viewPager.addOnPageChangeListener(this);    addView(view);  }

onFinishInflate()方法是自訂控制項中常用的一個方法,它表示從XML載入組件完成了,在該方法中我們通過LayoutInflater.from(context).inflate 擷取到個ViewPager對象和carouselLayout對象,並對pageItemWidth進行了賦值。
同時為viewPager設定addOnPageChangeListener。這裡別忘記調用addView();否則控制項就展示不了啦!

3、通過設定set方法來擷取資料,同時初始化介面效果
到這一步我們已經擷取到了展示輪播圖的ViewPager對象,那接下來要讓它展示你肯定想到了寫個類繼承PagerAdapter,然後重寫getCount,isViewFromObject,isViewFromObject,destroyItem等方法來讓ViewPager展示輪播圖。但是我們又不能寫得太固定,因為可能每個人想要展示的資料不一樣,所以我們定義一個介面來給外部使用的人寫自己的邏輯。上代碼:

//定義一個介面讓外部設定展示的Viewpublic interface Adapter{    boolean isEmpty();    View getView(int position);    int getCount();  }//ViewPager的適配器class ViewPagerAdapter extends PagerAdapter {    @Override    public int getCount() {      return totalCount;    }    @Override    public boolean isViewFromObject(View view, Object object) {      return view==object;    }    @Override    public Object isViewFromObject(ViewGroup container, int position) {      position %= showCount;      //調用介面的getView()擷取使用者要展示的View;      View view = adapter.getView(position);      container.addView(view);      return view;    }    @Override    public void destroyItem(ViewGroup container, int position, Object object) {      container.removeView((View) object);    }    @Override    public int getItemPosition(Object object) {      return super.getItemPosition(object);    }    @Override    public void finishUpdate(ViewGroup container) {      super.finishUpdate(container);      int position = viewPager.getCurrentItem();      //實現Viewpager到第一頁的實現能向左滑動      if (position==0){        position=showCount;        viewPager.setCurrentItem(position,false);      }else if (position==totalCount-1){//ViewPager到最後一頁的實現向又滑動        position = showCount - 1;        viewPager.setCurrentItem(position,false);      }    }  }//為外部提供設定資料來源的方法,同時為ViewPager做展示public void setAdapter(Adapter adapter){    this.adapter = adapter;    if (adapter!=null){      init();    }  }

上面的代碼就是定義了一個介面讓外部來設定資料,提供setAdapter來為adapter賦值,同時初始化介面效果,init()方法中就是資料的初始化,代碼如下:

private void init() {    viewPager.setAdapter(null);    carouselLayout.removeAllViews();//清空之前的資料    if (adapter.isEmpty()){      return;    }    int count = adapter.getCount();    showCount = adapter.getCount();    for (int i=0;i<count;i++){      View view = new View(context);      //用來做指標的View,通過state來做展示效果      if (currentPosition==i){        view.setPressed(true);        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + ConvertUtils.dip2px(context,3),pageItemWidth + ConvertUtils.dip2px(context,3));        params.setMargins(pageItemWidth, 0, 0, 0);        view.setLayoutParams(params);      }else {        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth,pageItemWidth);        params.setMargins(pageItemWidth,0,0,0);        view.setLayoutParams(params);      }      view.setBackgroundResource(R.drawable.carousel_layout_page);      carouselLayout.addView(view);    }    viewPager.setAdapter(new ViewPagerAdapter());    viewPager.setCurrentItem(0);    //讓手指觸碰到的時候自動輪播不起效    this.viewPager.setOnTouchListener(new OnTouchListener() {      @Override      public boolean onTouch(View v, MotionEvent event) {        switch (event.getAction()){          case MotionEvent.ACTION_DOWN:          case MotionEvent.ACTION_MOVE:            isUserTouched = true;            break;          case MotionEvent.ACTION_UP:            isUserTouched = false;            break;        }        return false;      }    });    mTimer.schedule(mTimerTask, 3000, 3000);  }

主要的邏輯代碼就是這樣啦,一個輪播圖的控制項就做好了。下面來看一下使用:

4、使用
xml中寫我們的輪播圖控制項:

<com.yangqiangyu.test.carouselview.CarouselView    android:layout_width="match_parent"    android:layout_height="220dp"> </com.yangqiangyu.test.carouselview.CarouselView>

java代碼中擷取控制項,同時設定介面

 CarouselView carouselView = (CarouselView) findViewById(R.id.CarouselView);  carouselView.setAdapter(new CarouselView.Adapter() {   @Override   public boolean isEmpty() {    return false;   }   @Override   public View getView(int position) {    View view = mInflater.inflate(R.layout.item,null);    ImageView imageView = (ImageView) view.findViewById(R.id.image);    imageView.setImageResource(mImagesSrc[position]);    return view;   }   @Override   public int getCount() {    return mImagesSrc.length;   }  });

返回是否為空白,在getView(int position)中return我們想返回的View,就是這麼簡單了啦。

希望本文所述對大家學習Android軟體編程有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.