自定义View之一-入门

1.四个方法

  • onMeasure()
  • onLayout()
  • onDraw()
  • onTouch()

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

  • 一个参数:new Button(context);
  • 两个参数:xml文件中使用
  • 三个参数:在控件有style属性时使用

3.三种测量模式

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

  • MeasureSpec.AT_MOST:在布局中指定了wrap_content
  • MeasureSpec.EXACTLY:在布局中指定了确定的值 100dp或者match_content
  • MeasureSpec.UNSPECIFIED:尽可能的大,很少能用到,ListView,ScrollView

4.自定义属性



    
        
        
    

    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();
    }


    


//自定义命名空间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.其他

  • 系统有的自定义属性,我们不能重新定义
  • 继承ViewGroup的控件默认不会执行onDraw()方法?

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

  • 在activity初始化之前需要使用view的宽高?
  1. onFoucusChange
  2. view.post
  3. view.getViewTreeObserver
  4. view.measure
  • getWidth()和getMeasuredWidth()的区别?

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

你可能感兴趣的:(自定义View之一-入门)