自定义View系列(二) 构造函数

来源:互联网 发布:java中dao怎么写 编辑:程序博客网 时间:2024/06/14 16:28

View的4个构造函数


其中,前2种必须要实现;
第3种在需要自定义xml属性的时候实现;
第4种是API 21后加入的,基本可以忽略。

  以LinearLayout的实现为例,第一个实际调用的是第二个,传默认参数null。以此类推
 public LinearLayout(Context context) {        this(context, null);    }    public LinearLayout(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }        public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {        this(context, attrs, defStyleAttr, 0);    }    public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

当我们使用 View view = new View(XxActivity.this) 来初始化View的时候,调用的是第一个构造函数View(Context)。

当我们使用xml,  findViewById(R.id.view)来初始化view的时候,调用的是第二个构造函数View(Context, AttributeSet)。

当我们使用xml并设置自定义属性的时候,我们需要实现第三个构造函数,并在第二个构造函数中手动调用第三个构造函数。

接下来给出例子:
首先自定义一个View,并且自定义一个String类型的属性
public class MyView extends View {    public MyView(Context context) {        super(context);        Log.d("thmtest|", "thmtest MyTextView(Context)");    }    public MyView(Context context, AttributeSet attrs) {        this(context, attrs, 0);        Log.d("thmtest|", "thmtest MyTextView(Context, AttributeSet)");    }    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        Log.d("thmtest|", "thmtest MyTextView(Context, AttributeSet, int)");        TypedArray a = context.obtainStyledAttributes(attrs,                 R.styleable.MyView                , defStyleAttr, 0);        String s = a.getString(R.styleable.MyView_default_str);        Log.d("thmtest|", "s = "+s);    }}
   <declare-styleable name="MyView">        <attr name="default_str" format="string" />    </declare-styleable>

在layout文件中声明一个MyView,并设置自定义属性值为"test"
注意,一定要写上这句:xmlns:MyView="http://schemas.android.com/apk/res-auto"
可以写在contentView上,也可以写在具体的View上
  <com.example.lading.applicationdemo.beans.MyView      xmlns:MyView="http://schemas.android.com/apk/res-auto"      android:id="@+id/myview"      android:layout_width="match_parent"      android:layout_height="match_parent"      MyView:default_str="test"      />

运行一下,日志如下:
11-14 15:08:30.945 18894-18894/com.example.lading.applicationdemo D/thmtest|: thmtest MyTextView(Context, AttributeSet, int)11-14 15:08:30.945 18894-18894/com.example.lading.applicationdemo D/thmtest|: s = test11-14 15:08:30.945 18894-18894/com.example.lading.applicationdemo D/thmtest|: thmtest MyTextView(Context, AttributeSet)
可以看到,test值已经Set进来了。

最后一下:
直接在代码中构造View调用View(Context)
在Xml中构造View调用View(Context , AttributeSet)
如果需要自定义属性,需要实现View(Context, AttributeSet, int), 并在View(Context, AttributeSet)中调用

第3种其实也不太用,我想主要是因为大多数人如我,
已经习惯了直接在代码中用get / set方法来设置属性了。
mark一下,如果用这种方法,为了保证属性及时set进去,要在onFinishInflate中做set操作。






0 0
原创粉丝点击