Android

Android自定义View基础

2018-11-05  本文已影响76人  luoqiang108

基础知识

View的构造函数

1. View(Context)
2. View(Context, AttributeSet)
<ImageView  
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:src="@drawable/icon" />
<declare-styleable name="ImageView">  
  <!-- Sets a drawable as the content of this ImageView. -->
  <attr name="src" format="reference|color" />
</declare-styleable>
public ImageView(Context context, AttributeSet attrs) {  
  TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageView, 0, 0);
  Drawable src = ta.getDrawable(R.styleable.ImageView_src);
  setImageDrawable(src);
  ta.recycle();
}
3. View(Context, AttributeSet, defStyleAttr)
  1. 在Theme(styles.xml)中设置样式
<resources>  
  <style name="Theme">
    <item name="mStyle">@style/CustomStyle</item>
  </style>

  <!--具体样式-->
  <style name="CustomStyle" >
    <item name="android:background">@android:color/black</item>
  </style>
</resource>
  1. 在构造方法中使用
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.view, R.attr.mStyle, 0);
4. View(Context, AttributeSet, defStyleAttr, defStyleRes)

它们是串联的,如果你调用了一个,所有的都会通过super被调用。串联还意味着你只需重写你需要的构造函数。一般来说,你只需实现前两个(一个用于代码,一个用于XML inflation)。

View视图结构

对于多View的视图,结构是树形结构:最顶层是ViewGroup,ViewGroup下可能有多个ViewGroup或View,如下图:

View树结构.png

注意:无论是measure过程、layout过程还是draw过程,永远都是从View树的根节点开始测量或计算(即从树的顶端开始),一层一层、一个分支一个分支地进行(即树形递归),最终计算整个View树中各个View,最终确定整个View树的相关属性。

Android坐标系

View位置(坐标)描述

Top:子View上边界到父view上边界的距离
Left:子View左边界到父view左边界的距离
Bottom:子View下边距到父View上边界的距离
Right:子View右边界到父view左边界的距离

View的位置.png

View位置获取方式

// 获取Top位置 
public final int getTop() { 
    return mTop; 
} 
// 其余如下:
getLeft(); //获取子View左上角距父View左侧的距离 
getBottom(); //获取子View右下角距父View顶部的距离 
getRight(); //获取子View右下角距父View左侧的距离
//get() :触摸点相对于其所在组件坐标系的坐标
 event.getX();       
 event.getY();

//getRaw() :触摸点相对于屏认坐标系的坐标
 event.getRawX();    
 event.getRawY();

具体如下图:


get() 和 getRaw() 的区别.png

Android的角度(angle)与弧度(radian)

Android中颜色相关内容

定义颜色的方式
//java中使用Color类定义颜色
int color = Color.GRAY; //灰色
//Color类中使用ARGB值表示颜色
int color = Color.argb(127, 255, 0, 0); //半透明红色
//使用十六进制定义颜色
int color = 0xaaff0000; //带有透明度的红色 
//Android中Color工具类 parseColor解析颜色字符串
int color = Color.parseColor("#FFFFFF")//白色
<?xml version="1.0" encoding="utf-8"?> 
<resources>
    //定义了红色(没有alpha(透明)通道) 
    <color name="red">#ff0000</color>
    //定义了蓝色(没有alpha(透明)通道) 
    <color name="green">#00ff00</color> 
</resources>
#f00 //低精度 - 不带透明通道红色 == #ff0000
#af00 //低精度 - 带透明通道红色 == #aaff0000
#ff0000 //高精度 - 不带透明通道红色 
#aaff0000 //高精度 - 带透明通道红色
引用颜色的方式
int color = getResources().getColor(R.color.mycolor);
<!--在style文件中引用-->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 
    <item name="colorPrimary">@color/red</item> 
</style> 

<!--在layout文件中引用在/res/values/color.xml中定义的颜色--> 
android:background="@color/red" 

<!--在layout文件中创建并使用颜色--> 
android:background="#ff0000" 

View的绘制流程

onMeasure():测量自己的大小,为正式布局提供建议。(注意,只是建议,至于用不用,要看onLayout);
onLayout():使用layout()函数对所有子控件布局;
onDraw():根据布局的位置绘图。

onMeasure()

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

MeasureSpec

  1. 模式分类
    它有三种模式:
  • UNSPECIFIED(未指定),父元素不对子元素施加任何束缚,子元素可以得到任意想要的大小;
  • EXACTLY(完全),父元素决定自元素的确切大小,子元素将被限定在给定的边界里而忽略它本身大小;
  • AT_MOST(至多),子元素至多达到指定大小的值。
  • wrap_content-> MeasureSpec.AT_MOST
  • match_parent -> MeasureSpec.EXACTLY
  • 具体值 -> MeasureSpec.EXACTLY
  1. 模式提取
    三种测量模式对应的二进制值分别是:

UNSPECIFIED=00000000000000000000000000000000
EXACTLY =01000000000000000000000000000000
AT_MOST =10000000000000000000000000000000
最前面两位代表模式,分别对应十进制的0,1,2;

//对应11000000000000000000000000000000;总共32位,前两位是1
int MODE_MASK  = 0xc0000000;
 
//提取模式
public static int getMode(int measureSpec) {
    return (measureSpec & MODE_MASK);
}
//提取数值
public static int getSize(int measureSpec) {
    return (measureSpec & ~MODE_MASK);
}

MeasureSpec.getMode(int spec) //获取MODE
MeasureSpec.getSize(int spec) //获取数值
int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
  • onMeasure()是用来测量当前控件大小的,给onLayout()提供数值参考,需要特别注意的是:测量完成以后通过setMeasuredDimension(int,int)设置给系统。
  • 我们可以给View设置LayoutParams,在View测量的时候,系统会将LayoutParams在父容器的约束下转换成对应的MeasureSpec,然后再根据这个MeasureSpec来确定View测量后的宽高。
  • 子view的大小由父view的MeasureSpec值和子view的LayoutParams属性共同决定。
  1. 实例
    当模式是MeasureSpec.EXACTLY时,我们就不必要设定我们计算的大小了,因为这个大小是用户指定的,我们不应更改。但当模式是MeasureSpec.AT_MOST时,也就是说用户将布局设置成了wrap_content,我们就需要将大小设定为我们计算的数值,因为用户根本没有设置具体值是多少,需要我们自己计算。即,假如width和height是我们经过计算的控件所占的宽度和高度。那在onMeasure()中使用setMeasuredDimension()最后设置时,代码应该是这样的:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
    int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
    int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
    int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
    
    //经过计算,控件所占的宽和高分别对应width和height
    //计算过程,我们会在onLayout中细讲
    …
    
    setMeasuredDimension((measureWidthMode == MeasureSpec.EXACTLY) ? measureWidth: width, (measureHeightMode == MeasureSpec.EXACTLY) ? measureHeight: height);
}

onLayout()

@Override
protected abstract void onLayout(boolean changed, int l, int t, int r, int b);

实例

<?xml version="1.0" encoding="utf-8"?>
<com.lg.www.animblog.MyLinLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ff00ff"
    tools:context=".MainActivity">

    <TextView android:text="第一个VIEW"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView android:text="第二个VIEW"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView android:text="第三个VIEW"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</com.lg.www.animblog.MyLinLayout>
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class MyLinLayout extends ViewGroup {
    public MyLinLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
        int height = 0;
        int width = 0;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            //测量子控件
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            //获得子控件的高度和宽度
            int childHeight = child.getMeasuredHeight();
            int childWidth = child.getMeasuredWidth();
            /*因为我们是垂直排列其内部所有的View,
            所以容器所占宽度应该是各个TextVIew中的最大宽度,所占高度应该是所有控件的高度和。*/
            width = Math.max(childWidth, width);
            height += childHeight;
        }
        setMeasuredDimension((measureWidthMode == MeasureSpec.EXACTLY) ? measureWidth : width, (measureHeightMode == MeasureSpec.EXACTLY) ? measureHeight : height);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int top = 0;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            int childHeight = child.getMeasuredHeight();
            int childWidth = child.getMeasuredWidth();
            child.layout(0, top, childWidth, top + childHeight);
            //垂直排列,上顶点依次累加
            top += childHeight;
        }
    }
}

getMeasuredWidth()与getWidth()

  • 首先getMeasureWidth()方法在measure()过程结束后就可以获取到了,而getWidth()方法要在layout()过程结束后才能获取到。
  • getMeasureWidth()方法中的值是通过setMeasuredDimension()方法来进行设置的,而getWidth()方法中的值则是通过layout(left,top,right,bottom)方法设置的。

还记得吗,我们前面讲过,setMeasuredDimension()提供的测量结果只是为布局提供建议,最终的取用与否要看layout()函数。大家再看看我们上面重写的MyLinLayout,是不是我们自己使用child.layout(left,top,right,bottom)来定义了各个子控件所应在的位置:

int childHeight = child.getMeasuredHeight();
int childWidth = child.getMeasuredWidth(); 
child.layout(0, top, childWidth, top + childHeight);

从代码中可以看到,我们使用child.layout(0, top, childWidth, top + childHeight);来布局控件的位置,其中getWidth()的取值就是这里的右坐标减去左坐标的宽度;因为我们这里的宽度是直接使用的child.getMeasuredWidth()的值,当然会导致getMeasuredWidth()与getWidth()的值是一样的。如果我们在调用layout()的时候传进去的宽度值不与getMeasuredWidth()相同,那必然getMeasuredWidth()与getWidth()的值就不再一样了。

onDraw()

onDraw1.png
onDraw2.png

感谢

深入理解Android View的构造函数
View的第三个构造函数的第三个参数defStyle
自定义View基础 - 最易懂的自定义View原理系列(1)
自定义控件三部曲视图篇(一)——测量与布局

上一篇 下一篇

猜你喜欢

热点阅读