美文网首页
自定义View之一-入门

自定义View之一-入门

作者: woochen123 | 来源:发表于2017-10-23 22:32 被阅读0次

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.自定义属性

<?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.其他

  • 系统有的自定义属性,我们不能重新定义
  • 继承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之一-入门

      本文链接:https://www.haomeiwen.com/subject/kerzuxtx.html