自定義scrollview時,遇到的坑

最近要實現一個自定義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的時候的小心點兒了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章