今天看啥  ›  专栏  ›  __Y_Q

自定义View_01_(入门篇)构造函数的调用

__Y_Q  · 简书  ·  · 2019-11-27 15:33

自定义 View 中 构造函数的调用

首先建一个 class 文件命名为 MyTextView, 继承自 View,重写三个构造函数,如下所示

public class MyTextView extends View {

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

一个参数的构造函数

一个参数的构造函数是在代码中创建对象的时候会被调用.

例如:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建对象的时候会被调用
        MyTextView textView = new MyTextView(this);
    }
}

两个参数的构造函数

两个参数的构造函数会在布局文件中使用这个View的时候被调用

例如:

<com.view.MyTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
    

三个参数的构造函数

三个参数的构造函数会在布局文件中使用 style 的情况下会被调用
例如:

  1. 现在 res/values/styles 文件中新建一个 style
    <style name="textViewDefault">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#666666</item>
    </style>
    
  2. 在布局文件中使用新建的 style
    <com.view.MyTextView
        style="@style/textViewDefault" />
    

第三种情况一般用于: 界面中一个控件存在大量的相同的属性的时候,可以使用这个方式来减少重复的工作量, 后期维护的时候只需要修改 style 属性即可达到全局修改的目的.也可用于 夜间/白天 模式的切换等场景.


不过实际开发中,我们一般不会这样写构造函数 (直接 super 父类), 有可能我们 A 界面是在代码中创建的控件, B界面又是在布局文件中直接声明的控件.....无法做到全部覆盖,所以基本都会采用如下写法

public MyTextView(Context context) {
    // 默认 super(context);
    this(context,null);
}

public MyTextView(Context context, @Nullable AttributeSet attrs) {
   // super(context, attrs);
    this(context, attrs,0);
}

public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    //TODO
}

让它们依次调用, 只需要在最后一个构造函数内嵌入我们想要嵌入的代码即可.




原文地址:访问原文地址
快照地址: 访问文章快照