自定義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文件裏面使用就可以。大笑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章