Inside the Android SDK TextView
itself 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 TextView
and ImageView
source code, the two-parameter constructor will call the three-parameter constructor and pass a style. When customizing View, you don't need to write.