自定义scrollview时,遇到的坑

博主在实现自定义ScrollView时遇到了滑动效果异常的问题,经过两个小时的排查,决定分享经验以防他人重蹈覆辙。文章预计将介绍问题的详细情况及解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近要实现一个自定义scrollview,然后在完成后发现滑动时并不是预期的效果,检查了很多次代码都没有发现bug(确保ontouchevent()方法正确)
折腾了两个多小时,特此记录,以示后人

首先看一下系统一般自定义view时习惯写的构造函数

public Song(Context context) {
        this(context,null);
    }

    public Song(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public Song(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a =context.getTheme().obtainStyledAttributes(attrs, R.styleable.song, defStyleAttr, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.song_text:
                    text = a.getString(attr);
                    break;
                case R.styleable.song_textsize:
                    textSize = a.getDimensionPixelSize(attr, (int) TypedValue
                            .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())
                    );
                    break;
                case R.styleable.song_textcolor:
                    textColor = a.getColor(attr, Color.YELLOW);
                    break;
                case R.styleable.song_cricleRadius:
                    cricleR = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                            20,getResources().getDisplayMetrics()
                            ));
                    break;

            }
        }

        a.recycle();
        mContext = context;
        mPaint = new Paint();
        Log.d("mPaint",mPaint.toString());
        mPaint.setColor(textColor);
    }
简单来说就是一参调用二参数,二参调用三参,本人在自定义view的时候也是习惯性的这么写,已经到了顺手拈来的地步,但是看一下scrollview的构造函数
 public ScrollView(Context context) {
        this(context, null);
    }

    public ScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.scrollViewStyle);
    }

    public ScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }
看到了吧。人家二参调用三参的时候有传入defStyleAttr,知道哪里错了吧,
所以以后再使用this的时候的小心点儿了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值