美文网首页
Android列表图片广告效果小结

Android列表图片广告效果小结

作者: Dane_404 | 来源:发表于2019-03-19 23:14 被阅读0次

1、效果图

2、实现

  • 首先,理解getIntrinsicWidth()、drawable.getBounds().width()、getWidth()
    getIntrinsicWidth():这个值和density有关,不同分辨率下Android系统自动缩放后的值。
    drawable.getBounds().width():绘制宽度。
    getWidth():View的宽度。

  • 自定义ImageView

    public class AdImageView extends AppCompatImageView {
      
      public AdImageView(Context context, @Nullable AttributeSet attrs) {
          super(context, attrs);
      }
    
      private int mDx;
      private int mMinDx;
    
      public void setDx(int dx) {
          if (getDrawable() == null) {
              return;
          }
          mDx = dx - mMinDx;
          if (mDx <= 0) {
              mDx = 0;
          }
          //图片的绘制高度-View的高度 = 最大可移动高度
          if (mDx > getDrawable().getBounds().height() - mMinDx) {
              mDx = getDrawable().getBounds().height() - mMinDx;
          }
          invalidate();
      }
    
      @Override
      protected void onSizeChanged(int w, int h, int oldw, int oldh) {
          super.onSizeChanged(w, h, oldw, oldh);
          mMinDx = h;  //控件高度
      }
    
      public int getDx() {
          return mDx;
      }
    
      @Override
      protected void onDraw(Canvas canvas) {
    
          Drawable drawable = getDrawable();
          int w = getWidth();
          //取drawable.getIntrinsicWidth()值来做比例计算,图片不会变形
          int h = (int) (getWidth() * 1.0f / drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight());
          drawable.setBounds(0, 0, w, h);
          canvas.save();
          canvas.translate(0, -getDx());   //canvas.translate移动的是绘制坐标
          super.onDraw(canvas);
          canvas.restore();
      }
    }
    
  • 接着是RecycleView滚动监听代码

     mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
          @Override
          public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
              super.onScrolled(recyclerView, dx, dy);
    
              int fPos = mLinearLayoutManager.findFirstVisibleItemPosition();  //获取第一个可见位置
              int lPos = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();  //获取最后一个完全可见位置
    
              for (int i = fPos; i <= lPos; i++) {
                  View view = mLinearLayoutManager.findViewByPosition(i);
                  AdImageView adImageView = (AdImageView) view.findViewById(R.id.id_iv_ad);
                  if (adImageView.getVisibility() == View.VISIBLE) {
                      //mLinearLayoutManager.getHeight() 就是获取了RecycleView的高度
                      adImageView.setDx(mLinearLayoutManager.getHeight() - view.getTop());
                  }
              }
          }
      });
    

相关文章

网友评论

      本文标题:Android列表图片广告效果小结

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