android 自定义viewPager 下标

    像一般商城类 app 的主界面 页面 顶部会有一个  广告展示窗口,如淘宝,京东等。这些广告在滚动的时候 都有一个下标表示 当前条目所处的 序列。

     如图: 

android 自定义viewPager 下标android 自定义viewPager 下标

android 自定义viewPager 下标

要实现这个效果 思路如下:

     下标用ImageView 实现 ,然后把所有的 下标都 放入 一个横向 的 LinearLayout中 ,通过 设置 LinearLayout的 gravity 控制 下标出现的 位置。

效果图:

android 自定义viewPager 下标

android 自定义viewPager 下标

具体实现:

       首先 这是个自定义控件,继承自LinearLayout ,需要一些自定义的 属性 比如

       count:  下标的数量

       checkedImg :  选中显示的图拍呢

<resources>
    <declare-styleable name="viewPagerIndex" >
        <attr name="checkImg" format="reference"/>
        <attr name="unCheckImg" format="reference"/>
        <attr name="count" format="integer"/>
        <attr name="checkIndex" format="integer"/>
    </declare-styleable>

</resources>

实例化时,先获取 布局文件中设置的属性

private void init(AttributeSet attrs) {
    TypedArray attributes = getResources().obtainAttributes(attrs, R.styleable.viewPagerIndex);
    checkImg = attributes.getResourceId(R.styleable.viewPagerIndex_checkImg, R.mipmap.ic_launcher);
    unCheckImg = attributes.getResourceId(R.styleable.viewPagerIndex_unCheckImg, R.mipmap.ic_launcher);
    count = attributes.getInt(R.styleable.viewPagerIndex_count, 0);
    checkIndex = attributes.getInt(R.styleable.viewPagerIndex_checkIndex, 0);
    LayoutInflater.from(getContext()).inflate(R.layout.view_viewpager_index_layout, this);
    LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.setLayoutDirection(HORIZONTAL);
    this.setLayoutParams(layoutParams);

    setContent();
}

然后 调用 setContent() 将 下标 添加 到 LinearLayout中:

/**
 * 添加 下标
 */
private void setContent() {
    this.removeAllViews();
    for (int i = 0; i < count; i++) {
        ImageView imageView = new ImageView(getContext());
        if (checkIndex == i) {
            imageView.setImageResource(checkImg);
            imageView.setTag(TAG_CHECKED);
        } else {
            imageView.setImageResource(unCheckImg);
            imageView.setTag(TAG_UN_CHECKED);
        }
        this.addView(imageView);
    }
}

如要 改变 选中下标 则 调用此方法:

/**
 * 设置 选中 下标 的 序号
 *
 * @param checkIndex
 */
public void setCheckIndex(int checkIndex) {
    this.checkIndex = checkIndex;
    ImageView imageViewChoosed = (ImageView) getChildAt(checkIndex);
    if (imageViewChoosed==null||TAG_CHECKED.equals(imageViewChoosed.getTag())) {
        // 如果 设置 下标序号 就是当前选中下标序号 则不做任何处理
        return;
    }
    // 将 当前选中下标改为 未选中,
    ImageView imageViewChecked = (ImageView) this.findViewWithTag(TAG_CHECKED);
    imageViewChecked.setImageResource(unCheckImg);
    imageViewChecked.setTag(TAG_UN_CHECKED);
    // 将设置的下标设置为选中
    imageViewChoosed.setImageResource(checkImg);
    imageViewChoosed.setTag(TAG_CHECKED);


}

项目地址:http://download.****.net/detail/qq_22911297/9868313

最终效果如图

android 自定义viewPager 下标android 自定义viewPager 下标

android 自定义viewPager 下标