The purpose of the three constructors of custom View

Inside the Android SDK TextViewitself is a custom View. This article takes TextView as an example to sort out the uses of the three construction methods.

one parameter constructor

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

It is often used in java code to create a new View object. For example:

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

Constructor with two parameters

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

The constructor with two parameters is used when xml parsing generates View objects. Therefore, if the custom View is to be placed in the xml file, a two-parameter constructor must be added. For the xml parsing process, you can refer to this article: Analysis of the process of creating View through xml generation in Android

Three parameter constructor

In the system TextViewand ImageViewsource code, the two-parameter constructor will call the three-parameter constructor and pass a style. When customizing View, you don't need to write.

Thanks: Custom View constructor, how much do you know?

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/131110384