返回

解构Android进阶之绘制-自定义View-自定义属性详解

Android





## Android进阶之绘制-自定义View-自定义属性详解

在自定义类继承View实现自定义控件的过程中,我们还应该对一些自定义属性有所了解。我们通过一个案例来学习一下。

新建一个Android Studio项目,并创建一个新的自定义View类,命名为MyView。

public class MyView extends View {

private int mBackgroundColor;
private int mTextColor;
private float mTextSize;

public MyView(Context context) {
    super(context);
    init(context, null);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context, attrs);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs);
}

private void init(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
    mBackgroundColor = a.getColor(R.styleable.MyView_backgroundColor, Color.WHITE);
    mTextColor = a.getColor(R.styleable.MyView_textColor, Color.BLACK);
    mTextSize = a.getDimension(R.styleable.MyView_textSize, 16);
    a.recycle();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setColor(mBackgroundColor);
    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

    paint.setColor(mTextColor);
    paint.setTextSize(mTextSize);
    canvas.drawText("MyView", 10, 20, paint);
}

}


```xml
<resources>
    <declare-styleable name="MyView">
        <attr name="backgroundColor" format="color" />
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>
<com.example.myapplication.MyView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background_color="#ff0000"
    android:text_color="#ffffff"
    android:text_size="20sp" />
MyView myView = findViewById(R.id.myView);

ValueAnimator animator = ValueAnimator.ofInt(0, 255);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        int value = (int) animation.getAnimatedValue();
        myView.setBackgroundColor(Color.argb(value, 0, 0, 0));
    }
});
animator.setDuration(1000);
animator.start();

通过以上代码,我们就可以通过XML来定义自定义View的自定义属性,并在自定义View中处理这些自定义属性,并使用这些自定义属性来实现属性动画。