美文网首页
自定义控件之viewpager导航,使用图片代替滑块

自定义控件之viewpager导航,使用图片代替滑块

作者: shada | 来源:发表于2016-05-29 22:23 被阅读113次

    特别申明:本文是在鸿洋大神的文章基础上实现的。我删减了一些代码,只是一个展示而已。
    效果如下:

    自定义控件之viewpager导航,使用图片代替滑块
    这是原文地址:http://blog.csdn.net/lmj623565791/article/details/42160391
    1.自定义属性
    <declare-styleable name="Indicator2">    
    <!--用作滑块的图片资源-->    
    <attr name="indicator" format="reference"></attr>    
    <!--初始状况下滑块距离屏幕左边的距离-->    
    <attr name="initTranslation" format="dimension"></attr>
    <!--可见滑块数量-->
    <attr name="visibleCount" format="integer"></attr></declare-styleable>
    

    2.获取自定义属性

    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Indicator2);
    int resourceId =array.getResourceId(R.styleable.Indicator2_indicator, R.mipmap.ic_launcher);
    bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
    initTranslation=array.getDimension(R.styleable.Indicator2_initTranslation,0);
    visibleTabCount=array.getInt(R.styleable.Indicator2_visibleCount,3);
    array.recycle();
    

    3.确定图片大小和位置

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {    
        super.onSizeChanged(w, h, oldw, oldh);   
        rectF = new RectF();    
        rectF.left=0;    
        rectF.top=getMeasuredHeight()-dp2px(15);    
        rectF.right= getScreenWidth()/visibleTabCount-2*initTranslation;   
        rectF.bottom= getMeasuredHeight()-dp2px(5);
    }
    

    4.绘制图片

    @Override
    protected void dispatchDraw(Canvas canvas) {    
       super.dispatchDraw(canvas);      
       canvas.save();   
       canvas.translate(initTranslation + mTranslationX, 0);      
       canvas.drawBitmap(bitmap,null,rectF,null);      
       canvas.restore();}
    

    5.添加tab文本和点击事件

    //设置tab文本和点击事件
    public void setTitles(List<String> list) {  
      if (list != null && list.size() > 0) {     
        removeAllViews();     
        for (int i = 0; i < list.size(); i++) {        
          TextView textView = new TextView(getContext());            
          LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);            
          params.width = getScreenWidth() / visibleTabCount;              
          textView.setGravity(Gravity.CENTER);            
          textView.setTextColor(Color.BLACK);            
          textView.setTextSize(10);            
          textView.setLayoutParams(params);            
          textView.setText(list.get(i));   
          addView(textView);       
         }   
         setItemClick();  
      }
    }
    //  点击事件
    private void setItemClick() { 
        for (int i = 0; i < getChildCount(); i++) {      
           final int finalI = i;     
           getChildAt(i).setOnClickListener(new OnClickListener() {   
               @Override          
               public void onClick(View v) {                  
                  mViewPager.setCurrentItem(finalI);            
              }       
           });    
        }
     }
    

    5.和viewpager联动

    public void setUpWidthViewPager(ViewPager viewPager,int pos) {  
      mViewPager = viewPager;   
      mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {       
           @Override       
           public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {           
              scroll(position, positionOffset);            
               if(mOnTabChangeListener!=null){                          
               mOnTabChangeListener.onPageScrolled(position,positionOffset,positionOffsetPixels);            
            }      
           }        
            @Override    
           public void onPageSelected(int position) {            resetTextViewColor(position);            if(mOnTabChangeListener!=null){     
               mOnTabChangeListener.onPageSelected(position);       
         }      
      }          
            @Override        
           public void onPageScrollStateChanged(int state) {   
             if(mOnTabChangeListener!=null){      
              mOnTabChangeListener.onPageScrollStateChanged(state);            
            }      
          }   
     });  
      mViewPager.setCurrentItem(pos);   
      resetTextViewColor(pos);
    }
    //改变indicator的颜色
    private void resetTextViewColor(int position) {    
        for (int i = 0; i < getChildCount(); i++) {      
            View view = getChildAt(i);    
            if (view instanceof TextView) {  
                if (position == i) {      
                    ((TextView) view).setTextColor(Color.RED);   
                 } else {    
                    ((TextView) view).setTextColor(Color.BLACK);   
                 }       
           }  
        }
    }
    private void scroll(int position, float positionOffset) {    
          mTranslationX =  (getMeasuredWidth() / visibleTabCount )*  (position + positionOffset);  
          int tabWidth = getScreenWidth() / visibleTabCount; 
          if (positionOffset > 0 && (position >= visibleTabCount - 2) && getChildCount() > visibleTabCount&& position < (getChildCount()-2)) { 
               if (visibleTabCount != 1) {   
                     scrollTo((position - (visibleTabCount - 2)) * tabWidth                    + (int) (tabWidth * positionOffset), 0);    
               } else {        
                    this.scrollTo(position * tabWidth + (int) (tabWidth * positionOffset), 0);      
              }  
      }  
          invalidate();
    }
    
    

    6.一些工具类和对外暴露的接口

      //获取屏幕宽度
      private int getScreenWidth(){   
     return getResources().getDisplayMetrics().widthPixels;}
    //dp转px
    private int dp2px(int dp) {   
     return (int) (getResources().getDisplayMetrics().density * dp + 0.5);}
    private OnTabChangeListener mOnTabChangeListener;
    public interface OnTabChangeListener{  
      void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);   
      void onPageSelected(int position);  
      void onPageScrollStateChanged(int state);
    }
    public void setOnTabChangeListener(OnTabChangeListener onTabChangeListener){ 
       this.mOnTabChangeListener=onTabChangeListener;
    }
    

    相关文章

      网友评论

          本文标题:自定义控件之viewpager导航,使用图片代替滑块

          本文链接:https://www.haomeiwen.com/subject/zzhqdttx.html