国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android自定義圖片輪播Banner控件使用解析

2019-10-22 18:10:46
字體:
來源:轉載
供稿:網友

圖片輪播控件,可以說是每個App基本上都會用到的。它可以用來動態的展示多個圖片,之前寫過兩篇博客:實現ViewPager無限循環的方式一實現ViewPager無限循環的方式二,在這兩篇博客中,分析了兩種實現ViewPager無限循環的原理,但是在使用的過程中,代碼的解偶性很低,所以就使用自定義View的方式,實現無限循環的圖片輪播的封裝。

先看看效果:

Android,圖片輪播,Banner控件

功能特點

  1. 支持自定義寬高比例
  2. 支持自定義圖片切換時間
  3. 支持自定義指示點的顏色
  4. 支持自定義指示點的背景色
  5. 支持自定義指示點的高度
  6. 支持是否顯示指示點
  7. 支持每個圖片設置不同的點擊事件

使用簡單

 <com.xiaomai.bannerview.BannerView    android:id="@+id/bannerView"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    app:aspectRatio="1.5"    app:defaultSrc="@mipmap/ic_launcher"    app:indicatorBackground="@color/white"    app:indicatorHeight="50dp"    app:indicatorPositionSize="8dp"    app:updateTime="3000" />

實現步驟

  • 聲明自定義的屬性
  • 創建一個類繼承RelativeLayout
  • 解析屬性

聲明自定義的屬性

在values/attrs文件中創建自定義的屬性

<resources>  <declare-styleable name="BannerView">    <attr name="aspectRatio" format="float" />  <!-- 寬高比 -->    <attr name="defaultSrc" format="integer|reference" />   <!-- 占位圖 -->    <attr name="updateTime" format="integer" />   <!-- 圖片切換時間 -->    <attr name="indicatorVisible" format="boolean" /> <!-- 是否顯示指示器 -->    <attr name="indicatorHeight" format="dimension" /> <!-- 指示器的高度 -->    <attr name="indicatorBackground" format="color|reference" />  <!-- 指示器的背景顏色 -->    <attr name="indicatorPositionSize" format="dimension" /> <!-- 指示點的大小 -->  </declare-styleable></resources>

創建BannerView類

public class BannerView extends RelativeLayout {  public BannerView(Context context) {    this(context, null);  }  public BannerView(Context context, AttributeSet attrs) {    this(context, attrs, 0);  }  public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);}

在BannerView中聲明變量屬性

 

private Context context;  private Handler handler;  private ImageLoader imageLoader;  private DisplayImageOptions options;  private boolean isHaveHandler = true;// 當用戶點擊輪播圖時,取消handler隊列,也就是取消滾動  // 控件Start  private ViewPager viewPager;  private LinearLayout indicator;// 指示器  private onItemClickListener listener;  // 控件End  // 自定義屬性Start  private float mAspectRatio; // 寬高比  private int defaultImageResource; // 默認占位圖  private int updateTime; // 圖片切換的時間間隔,默認3秒  private boolean showIndicator; // 是否顯示指示器,默認顯示  private int indicatorHeight;// 指示器的高度,默認35dp  private int indicatorPositionSize; // 指示器的大小  private int indicatorBackground; // 指示器的背景顏色  // 自定義屬性End  // 數據Start  private int imageCount;  private int lastPosition;  private List<Integer> imageResources;  private List<Image> imageUrls;  // 數據End

解析自定義屬性的值

接下來為自定義的屬性賦值,在3個參數的構造方法中初始化變量。

 

public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);    parseCustomAttributes(context, attrs);    this.context = context;    handler = new Handler();    imageLoader = ImageLoader.getInstance();    options = HSApplication.getDisplayOptions().build();    initViews();  }  /**   * 解析自定義屬性   *   * @param context   * @param attrs   */  private void parseCustomAttributes(Context context, AttributeSet attrs) {    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BannerView);    mAspectRatio = typedArray.getFloat(R.styleable.BannerView_aspectRatio, 0f);    defaultImageResource = typedArray.getResourceId(R.styleable.BannerView_defaultSrc,        R.drawable.about_us);    updateTime = typedArray.getInt(R.styleable.BannerView_updateTime, 3000);    showIndicator = typedArray.getBoolean(R.styleable.BannerView_indicatorVisible, true);    indicatorHeight = (int) (typedArray.getDimension(R.styleable.BannerView_indicatorHeight,        Utils.dip2px(context, 35)));    indicatorBackground = typedArray.getResourceId(R.styleable.BannerView_indicatorBackground,        R.color.white_alpha00);    indicatorPositionSize = (int) typedArray.getDimension(        R.styleable.BannerView_indicatorPositionSize, Utils.dip2px(context, 5));    typedArray.recycle();  }  private void initViews() {    viewPager = new ViewPager(context);    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {      @Override      public void onPageScrolled(int position, float positionOffset,          int positionOffsetPixels) {      }      @Override      public void onPageSelected(int position) {        if (showIndicator) {          for (int i = 0; i < indicator.getChildCount(); i++) {            indicator.getChildAt(i).setSelected(false);          }          indicator.getChildAt(position % imageCount).setSelected(true);        }        lastPosition = position;      }      @Override      public void onPageScrollStateChanged(int state) {        switch (state) {          case ViewPager.SCROLL_STATE_IDLE:// 空閑狀態            if (!isHaveHandler) {              isHaveHandler = true;              handler.postDelayed(updateRunnable, updateTime);            }            break;          case ViewPager.SCROLL_STATE_DRAGGING:// 用戶滑動狀態            handler.removeCallbacks(updateRunnable);            isHaveHandler = false;            break;        }      }    });    addView(viewPager, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,        ViewGroup.LayoutParams.WRAP_CONTENT));    if (showIndicator) {      indicator = new LinearLayout(context);      indicator.setOrientation(LinearLayout.HORIZONTAL);      indicator.setGravity(Gravity.CENTER);      indicator.setBackgroundResource(indicatorBackground);      RelativeLayout.LayoutParams layoutParams = new LayoutParams(          ViewGroup.LayoutParams.MATCH_PARENT, indicatorHeight);      layoutParams.addRule(ALIGN_PARENT_BOTTOM);      addView(indicator, layoutParams);    }}

控件和自定義的屬性都經過賦值和初始化了,接下來,該為設置圖片資源了。

 

 public void setImageResources(List<Integer> imageResources) {    if (imageResources == null || imageResources.size() == 0) {      throw new RuntimeException("圖片資源為空");    }    this.imageResources = imageResources;    imageCount = imageResources.size();  }  public void setImageUrls(List<Image> imageUrls) {    if (imageUrls == null || imageUrls.size() == 0) {      throw new RuntimeException("圖片地址資源為空");    }    this.imageUrls = imageUrls;    imageCount = imageUrls.size();    loadImages();  }  private void loadImages() {    if (showIndicator) {      addIndicationPoint();    }    viewPager.setAdapter(new MyViewPageAdapter());    viewPager.setCurrentItem(200 - (200 % imageCount));    handler.removeCallbacks(updateRunnable);    handler.postDelayed(updateRunnable, updateTime);  }  /**   * 添加指示點到指示器中   */  private void addIndicationPoint() {    // 防止刷新重復添加    if (indicator.getChildCount() > 0) {      indicator.removeAllViews();    }    View pointView;    int margin = Utils.dip2px(context, 5f);    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(        indicatorPositionSize, indicatorPositionSize);    layoutParams.setMargins(margin, margin, margin, margin);    for (int i = 0; i < imageCount; i++) {      pointView = new View(context);      pointView.setBackgroundResource(R.drawable.indicator_selector);      if (i == lastPosition) {        pointView.setSelected(true);      } else {        pointView.setSelected(false);      }      indicator.addView(pointView, layoutParams);    }  }  private class MyViewPageAdapter extends PagerAdapter {    @Override    public int getCount() {      return Integer.MAX_VALUE;    }    @Override    public boolean isViewFromObject(View view, Object object) {      return view == object;    }    @Override    public Object instantiateItem(ViewGroup container, final int position) {      final ImageView imageView = new ImageView(container.getContext());      imageView.setImageResource(defaultImageResource);      imageView.setScaleType(ImageView.ScaleType.FIT_XY);      final Image image = imageUrls.get(position % imageCount);      imageLoader.displayImage(image.getImageUrl(), imageView, options);      imageView.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {          if (listener != null) {            listener.onClick(v, position % imageCount, image.getAction(),                image.getUrl());          }        }      });      container.addView(imageView);      return imageView;    }    @Override    public void destroyItem(ViewGroup container, int position, Object object) {      container.removeView((View) object);    }  }  private Runnable updateRunnable = new Runnable() {    @Override    public void run() {      viewPager.setCurrentItem(lastPosition + 1);      handler.postDelayed(updateRunnable, updateTime);    }/**   * 點擊監聽回調事件   */  public interface onItemClickListener {    void onClick(View view, int position, String action, String url);  }  public void setOnItemClickListener(onItemClickListener listener) {    this.listener = listener;  }

時間太倉促,解釋的不是太詳細,可以移步我的GitHub查看完整代碼。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西乌珠穆沁旗| 湘乡市| 张北县| 陆良县| 黄冈市| 阿拉尔市| 岑巩县| 怀集县| 内丘县| 石门县| 甘德县| 乐山市| 榆中县| 河池市| 类乌齐县| 冀州市| 平武县| 天峨县| 溧水县| 明水县| 秦皇岛市| 井陉县| 昂仁县| 三门县| 高要市| 北川| 周宁县| 金沙县| 民和| 阿鲁科尔沁旗| 隆德县| 富川| 得荣县| 织金县| 淅川县| 宁安市| 荔浦县| 西乡县| 扎赉特旗| 田东县| 甘洛县|