自定义View之一-入门

2017-10-23  本文已影响0人  woochen123

1.四个方法

2.三个构造函数使用场景

3.三种测量模式

MeasureSpec
为了减小分配对象的内存开销,MeasureSpec是一个整型值(30位表示大小+2位表示模式)。它表示父类view传递给子类view的一种测量规范(子view的测量由父类的MeasureSpec和自身的layoutParam时共同决定)

4.自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="test">
        <attr name="text" format="string" />
        <attr name="testAttr" format="integer" />
    </declare-styleable>
</resources>
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test);
        String text = ta.getString(R.styleable.test_testAttr);
        int textAttr = ta.getInteger(R.styleable.test_text, -1);
        ta.recycle();
    }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:woochen="http://schemas.android.com/apk/res/com.example.test"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.test.MyTextView
        android:layout_width="100dp"
        android:layout_height="200dp"
        woochen:testAttr="520"
        woochen:text="helloworld" />

</RelativeLayout>
//自定义命名空间xmlns->xml name space  com.example.test->包名
xmlns:woochen="http://schemas.android.com/apk/res/com.example.test"
//常用
xmlns:app="http://schemas.android.com/apk/res-auto" 

4.其他

解决方案(改变flag的值):1.给控件设置一个background 2. setWillNotDraw(false); 3.重写 dispatchDraw(canvas);

  1. onFoucusChange
  2. view.post
  3. view.getViewTreeObserver
  4. view.measure

赋值时间不同,一个在measure阶段,一个在layout阶段

上一篇 下一篇

猜你喜欢

热点阅读