1.自定义View简介
自定义View可以认为继承自View,系统没有的效果(ImageView,TextView,Bottun),extends View,extends ViewGroup
2.onMeasure 自定义View的测量方法
获取宽高
//获取宽高的模式
int widthMode = MeasureSpec.getMode(widthMeasureSpec); //获取前两位
int heightMode = MeasureSpec.getSize(heightMeasureSpec);
MeasureSpec.AT_MOST 在布局中指定了wrap_content
MeasureSpec.EXACTLY 在布局中指定了确切的值 100dp match_parent fill_parent
MeasureSpec.UNSPECIFIED 尽可能的大,很少能用到,ListView , ScrollView 在测量子布局的时候会用UNSPECIFIED
// 获取宽高的值
int widthSize = MeasureSpec.getSize(widthMeasureSpec); // 获取后面30位
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
ScrollView + ListView 会显示不全问题
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//解决显示不全的问题
heightMeasureSpec = MeasureSpec.makeMeasureSpec
(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
widthMeasureSpec widthMeasureSpec : 会包含两个信息是一个32位的值,第一个信息是模式:2位 值:30位
3.onDraw() 用于绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(); //花文本
canvas.drawArc(); //画弧
canvas.drawCircle(); //画圆
}
4.onTouch() 处理跟用户交互的
/**
* 处理跟用户交互的,手指触摸等等
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//手指按下
Log.e("TAG", "onTouchEvent: 手指按下" );
break;
case MotionEvent.ACTION_UP:
//手指抬起
Log.e("TAG", "onTouchEvent: 手指抬起");
break;
case MotionEvent.ACTION_MOVE:
//手指移动
Log.e("TAG", "onTouchEvent: 手指移动");
break;
}
return super.onTouchEvent(event);
}
5.自定义属性()
自定义属性就是用来配置的,android:text="ItJs"是系统的一个自定义属性
5.1在res下的values创建attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--name自定义View名字TextView-->
<declare-styleable name="TextView">
<!--name属性名称
format格式:string文字 color 颜色
dimension 宽高 字体大小
-->
<attr name="text" format="string"/>
<attr name="textColor" format="color"/>
<attr name="testSize" format="dimension"/>
<attr name="maxLength" format="integer"/>
<attr name="background" format="reference|color"/>
<attr name="inputType">
<enum name="number" value="1" />
<enum name="text" value="2" />
<enum name="password" value="3"/>
</attr>
</declare-styleable>
</resources>
5.2 在布局中使用
声明命名空间,然后在自己的自定义View中使用
xmlns:app="http://schemas.android.com/apk/res-auto"
<com.itjs.myapplication.TextView
app:text="你好"
app:textColor="#03A9F4"
app:inputType="text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
5.3 在自定义View中获取属性
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TextView);
mTextColor = array.getColor(R.styleable.TextView_textColor,mTextColor);
mTextSize = array.getDimensionPixelSize(R.styleable.TextView_testSize,mTextSize)