Android 自定义View 学习笔记 1

Android 自定义View 学习1

1.第一节

自定义view 简介

自定义view可以认为继承自View 系统未提供的View(或者效果) extends View extends ViewGroup

  1. View里面的构造函数分别是在什么时候调用
    在这里插入图片描述

  2. ** 自定义View 测量方法(onMeasure())**

// 获取宽高的模式
int width = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getMode(heightMeasureSpec;

//三种模式
MeasureoSpec.AT_MOST:在布局中指定了 wrap_content
MeasureSpec.EXACTLY:在布局中指定了确切的值 比如 100dp
MeasureSpec.UNSPECIFIED:尽可能的大,很少用到,在listview scrollview配合使用的时候用到

ScrollView + ListView 会显示不完整的问题解决方式
测量计算高度,重新设置高度(自定义listview解决如下图)
在这里插入图片描述

3.** 自定义View 绘制方法(onDraw())**

canvas.drawText();       //画文本

canvas.drawArc();        //画弧

canvas.drawCircle();    //画圆

4.** 自定义View 处理跟用户交互方法(onTouch())**

三种状态
MotionEvent.ACTION_DOWN    //手指按下
MotionEvent.ACTION_MOVE    //手指移动
MotionEvent.ACTION_UP         //手指抬起

5.** 自定义View 自定义属性(用来配置)**

1.在attrs.xml文件中定义
<resources>
    // 自定义TextView
    <declare-styleable name="TextView">
        // name 是名称,format是格式  color(颜色),string(文本),dimension(sp,dp)...
        <attr name="textColor" format="color"/>
        <attr name="text" format="string"/>
        <attr name="textSize" format="dimension"/>
    </declare-styleable>
</resources>
2.在布局文件中使用
<com.darren.view.TextView
        // app: 自定义属性
        app:text="自定义文本"
        app:textColor="@color/colorAccent"
        app:textSize="18sp"
        // android: 系统自带的属性
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />
3.在代码中获取自定的属性
public TextView(Context context) {
    this(context,null);
}

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

public TextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    // 获取TypedArray
    TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.TextView);
    // 获取文本
    mText = typedArray.getText(R.styleable.TextView_text);
    // 获取文字颜色
    mTextColor = typedArray.getColorStateList(R.styleable.TextView_textColor);
    // 获取文字大小
    mTextSize = typedArray.getDimensionPixelSize(R.styleable.TextView_textSize,mTextSize);
    // 回收
    typedArray.recycle();
}

猜你喜欢

转载自blog.csdn.net/u010689434/article/details/111182150