自定义View的三个构造函数的用途

Android SDK里面的TextView,本身就是一个自定义的View。本文以TextView为例,梳理三个构造方法的用途。

一个参数的构造函数

    public TextView(Context context) {
    
    
        this(context, null);
    }

常用于java代码new一个View对象。例如:

public class MainActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        // 创建TextView对象,并设置属性
        TextView textView = new TextView(this);
        textView.setText(R.string.app_name);
        textView.setTextSize(30);
        // 把TextView对象添加到布局中
        setContentView(textView);
    }
}

两个参数的构造函数

    public TextView(Context context, @Nullable AttributeSet attrs) {
    
    
        this(context, attrs, com.android.internal.R.attr.textViewStyle);
    }

两个参数的构造函数,用于xml解析生成View对象的时候。所以自定义View如果要放到xml文件中,必须要添加两参数的构造函数。xml解析过程,可以参考这篇文章:Android通过xml生成创建View的过程解析

三个参数个构造函数

系统TextViewImageView的源码中,两参构造函数会调用三个参数的构造函数,传递了一个style。自定义View时,可以不写。

感谢:自定义View构造函数,知多少?

猜你喜欢

转载自blog.csdn.net/zhangjin1120/article/details/131110384