自定义viewPager下面的导航按钮

要实现viewPager下面的导航按钮,为了方便,我们建立一个自定义view来复用,用起来也方便

首先要新建一个类NavImgLayout集成LinearLayout.

在构造方法里解析自定义属性

/**
	 * 解析属性
	 * @param attrs
	 */
	private void paresAttr(AttributeSet attrs) {
		TypedArray ta = getResources().obtainAttributes(attrs, R.styleable.navattr);
		checkedimg = ta.getResourceId(R.styleable.navattr_checkedimg, 0);
		uncheckedimg = ta.getResourceId(R.styleable.navattr_uncheckedimg,0);
		imgcount = ta.getInt(R.styleable.navattr_count, 0);
	}

这里分别定义三个属性,一个数选中的图片一个是未选中的图片,一个是按钮的数量,分别对这三个对象进行赋值

然后初始化按钮

	private void initView() {
		params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		params.leftMargin = 5;
		params.rightMargin = 5;
		this.setGravity(Gravity.CENTER);
		
		if(imgcount > 0){
			for (int i = 0; i < imgcount; i++) {
				ImageView iv = new ImageView(getContext());
				if(i==index){
					iv.setImageResource(checkedimg);
					iv.setTag("checked");
				}else{
					iv.setImageResource(uncheckedimg);
				}
				iv.setLayoutParams(params);
				this.addView(iv);
			}
		}
		
	}

设置每个按钮的布局属性

提供一些对外的接口方便用户操作微笑

//下一个选项
public void next(){
		if(index != imgcount-1){
			index ++;
			selectByIndex(index);
		}
	}
//设置按钮数量
	public void setCount(int imgcount){
        this.imgcount = imgcount;
        initView();
    }
//上一个选项
	public void above(){
		if(index != 0){
			index--;
			selectByIndex(index);
		}
	}
根据坐标改变imageview的属性
 public void selectByIndex(int index){
        ImageView checkedIv = (ImageView) this.findViewWithTag("checked");
        checkedIv.setImageResource(uncheckedimg);
        checkedIv.setTag(null);

        ImageView iv = (ImageView) this.getChildAt(index);
        iv.setImageResource(checkedimg);
        iv.setTag("checked");
    }


这样就完成了一个自定义navGroup的,以后要使用直接在xml文件里面使用就可以。大笑

猜你喜欢

转载自blog.csdn.net/zz6880817/article/details/50781142