您的位置:首页 > 移动开发 > Android开发

Android 自定义View基础知识

2018-02-23 11:10 471 查看
Android中的控件分为两类,要么是继承View类的控件,要么是继承ViewGroup类的控件,而ViewGroup类也继承了ViewGroup类。

1.View的四个构造方法
自定义View的时候,继承View类,至少需要实现一个构造方法。public class CircleView extends View {
//如果View是在Java代码中new的,则调用第一个构造方法
public CircleView(Context context) {
super(context);
}
//如果View是在XML中声明的,则调用第二个构造方法,自定义的属性可以通过AttributeSet得到
public CircleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
//不会自动调用,一般在第二个构造方法中调用
public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//API21及以后才使用,不会自动调用,一般在第三个构造方法中调用
public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}第三和第四个构造方法中的defStyleAttr和defStyleRes参数与主题相关,具体可以看这篇文章,不能再详细:Android View 四个构造函数详解
2.Android中的坐标系
屏幕左上角为坐标原点,向右为x轴增大方向,向下为y轴增大方向
3.View的位置
View的位置由四个顶点决定
Top:子View左上角距父View顶部的距离
Left:子View左上角距父View左侧的距离
Bottom:子View右下角距父View顶部的距离
Right:子View右下角距父View左侧的距离
可通过view.getxxx()函数进行获取,如getTop(),表示获取子View左上角距父View顶部的距离
4.MotionEvent()中get()和getRaw()的区别
event.getX(),event.getY()表示触摸点相对于View左上角为坐标原点的坐标系
event.getRawX(),event.getRawY()表示触摸点相对于屏幕左上角为坐标原点的坐标系
5.Android中的角度和弧度
deg为角度,rad为弧度,360 deg = 2π rad,  (π/180) x deg = rad,(180/π) x rad = deg
在默认的屏幕坐标系中,角度增大方向为顺时针
6.Android中的颜色值
ARGB8888 四通道高精度32位ARGB4444 四通道低精度16位RGB565 Android屏幕的默认模式16位Alpha8 仅有透明通道8位以我们最常用的,也是官方推荐的ARGB8888为例,A(Alpha)表示透明度,R(Red)表示红色,G(Green)表示绿色,B(Blue)表示蓝色,以上表示四个通道,后面的四个8,代表每个通道对应用8位的二进制数来表示。每个通道的8位二进制数的范围是从00000000至11111111,转换为十进制的范围是0至256,转换为十六进制的范围是0x00至0xFF。定义颜色在java代码中定义 //使用Color类定义颜色
int color = Color.GRAY; //灰色
//使用ARGB值定义颜色
int color = Color.argb(127, 255, 0, 0); //半透明红色
int color = 0xaaff0000; //带有透明度的红色在XML中定义<?xml version="1.0" encoding="utf-8"?>
<resources>
//定义了红色(没有alpha(透明)通道)
<color name="red">#ff0000</color>
</resources>引用颜色
在java中引用XML定义的颜色//方法1
int color = getResources().getColor(R.color.mycolor);

//方法2(API 23及以上)
int color = getColor(R.color.myColor); 在XML中引用或者创建颜色 <!--在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"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android