Interface activity drawing display of Android system programming introduction series


Last articleThe interface is introducedActivityThe startup mode and life cycle of this article will continue to be introduced in the interfaceActivityHow the content in is drawn and displayed to the user.

Run the newly created interface on the Android systemActivtiy, the display to the user is blank. Thanks to the powerful template support of Android studio, the newly created interfaceActivityIt will be rewritten automaticallyonCreate()Method and automatically create the following two lines of similar default code within the method.


obviously,setContentView()The method is to load the current interfaceActivityXXX in the parameter named refers to the file name, which is called the layout file. stayFirst article in a seriesMentionedresDirectory is the folder where application resources are stored. There is a folder namedlayoutThe directory of is dedicated to storing layout files.
In Android studio, justlayoutCreate a layout file in the directoryjavaIn the source code under the directoryR.layoutA constant with the same name as the layout file in which the class name isRThe file is injava(generate)Automatically generated under the current application package name of the directory.

The newly created layout file in Android studio generates the following template by default. The file conforms to the XML file format. The tag name can only be the control name defined by the Android system or customized in our application, and its properties can only use the defined properties.


View view is the basic unit class for drawing graphics in Android system, and it is also the basic unit class for system interaction with users. All view classes trace their parent classes and can be traced back to the same parent classandroid.view.View

If you add a view directly to the layout file, the view is calledStatic loadingof Static view creation requires a large number of layout files, which takes up a lot of storage space when the application is packaged. However, after the application is installed, the Android system will draw these views more quickly.
On the contrary, it can also be in the current interface of the source code fileActivityIn, directly call the constructor of the view class to create a view and load it into the current interfaceDynamic loadingof Dynamically created views are written into the source code, so the application package will not occupy too much storage space, but after the application is installed and running, the Android system needs more time to parse and draw these views.
Although the above two view loading methods are different, they are not very different in lightweight applications that do not involve a large number of view loading. Generally, there are a fixed number of views in the interface, which can be created statically directly. In this way, the layout effect of the current interface can be previewed in real time with the help of the layout preview plug-in of Android studio; Only when a large number of interfaces are dynamically changed by loading different views according to different data, the way of dynamically loading views may be more convenient.

In addition to creating and loading views, you can also modify themattributeIn order to facilitate the Android system to distinguish drawing, similarly, you can dynamically set the default attribute value during static loading, or you can dynamically set the attribute value in the source code.

Note: for the same attribute, the dynamic setting result will override the static attribute value first.

After any view is created and loaded, two attribute values must be specified, that is, the dimensions representing the width and height of the view. In the layout file, the statically loaded view must be in the labelandroid:layout_widthandandroid:layout_heightAttribute setting; In the source code, the default width and height of dynamically loaded views areLayoutParams.WRAP_CONTENT, representing the adaptive content size, or you can call the.layoutParams.widthand.layoutParams.heightVariables can be accessed or modified directly.

According to the tasks of the view, it can be roughly divided into three types: container view, display view and edit view.

  1. The container class view generally conforms to the naming specification with the suffix layout. It can be used as the parent view and continue to load and draw child views within it, including display class view and edit class view. Commonly used are linear layouts that line up the sub view positionsandroid.widget.LinearLayout, relative layout drawn with relative position for subviewsandroid.widget.RelativeLayout, combine the advantages of the above two layouts to draw the constrained layout of the relative position of sub views more flexiblyandroidx.constraintlayout.widget.ConstraintLayoutWait.
  2. The display class view can be understood as an output view. It is generally a subclass of the container class view and conforms to the naming specification with the suffix view. It is mainly responsible for displaying data resources to users in a more intuitive form. It’s like showing the content of the textandroid.widget.TextView, showing picturesandroid.widget.ImageView, showing the videoandroid.widget.VideoViewWait.
  3. Edit class view can be understood as input view, which is generally a subclass of display class view or container class view, and the naming does not comply with the naming specifications of the above two types. You can change the relevant attributes of your own view in real time according to the user’s control. For example, it allows users to input text and display the input results in real timeandroid.widget.EditText, allowing the user to select the time and display theandroid.widget.TimePickerDisplayed when the user needs a promptandroid.widget.ToastWait.

System view

As the above examples, the views are defined in the Android SDK, which is called the system view. System views are located inandroid.widgetUnder the bag.
In daily development, you only need to master how to use the system view. Here, several common view cases are introduced in the way of dynamic loading.

The first is the interfaceActivityFor the corresponding layout file, take the template layout file automatically generated by Android studio in the above article as an example. In order to obtain the root view of the layout file in the source code, in the root viewAdd in labelandroid:idAttribute, attribute value in@+id/The beginning indicates a new attribute value, and any value can be defined; And if@id/At the beginning, only defined property values can be used. All new properties are automatically stored in the previously mentioned by Android studioRFile, in the source code, you, where XXX is the defined attribute value.


Then you can use the interface of the source codeActivityGet the view and operate the view, such as adding sub views.

val rootLayout = findViewById(

        val button1=Button(this)
        Button1. Text = "button"

        val textView1=TextView(this)
        Textview1. Text = "text display area"

        val layoutParamsButton1 = ConstraintLayout.LayoutParams(
        layoutParamsButton1.topMargin = 500

        val layoutParamsTextView1 = ConstraintLayout.LayoutParams(


Useful in the above Because its binding view is not statically loaded in the layout file, the ID value corresponding to the view can only be declared separately in the resource fileresCreate a new resource file in XML format under the resource directory, and add the following code to create an ID for use in the above source code.

Finally, the running effect of the above code is shown in the figure below.

Custom view

Although the system view provided by the Android SDK can meet most common scenarios, the fun of development lies in the free drawing of views and interaction. Android also allows developers to freely define views to meet their special needshobbyDemand. It must be understood without emphasis that this custom view can only be used in the module that defines the view, or in the dependent sub module of the module that defines the custom view. For a custom view, its related properties may vary from view to view, but the use method is similar to that of the system view, so you mainly master how to define a custom view. Here, take the user-defined input box as an example.

To customize a view, first define a view class in the source code, which mustinheritsinceandroid.view.ViewOr its subclasses. When introducing the view classification, you can find that the container class view is the parent of the other two views. Therefore, when the editing class view and the presentation class view do not meet the needs of the user-defined view, the container class view is directly selected as the parent class of the user-defined view instead of directly inheritingandroid.view.View。 If the requirements of a user-defined view coincide with the functions of an edit class view or display class view, you can modify it directly. You can directly inherit the edit class view or display class view.

After inheriting the view class, the Java language needs to override the three properties of the custom viewConstruction method, if the application is running on Android 5.0 and above, you need to rewrite the fourth construction method.

The Android version number is 5.0, corresponding to the Android API level of 21, and the corresponding Android version is called lollipop for short

public MyEditText(Context context) {
		//This constructor is called when the view is loaded dynamically
        this(context, null);

    public MyEditText(Context context, AttributeSet attrs) {
		//This constructor is called when the view is statically loaded
        this(context, attrs, 0);

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		//Ensure that other constructor methods eventually call the constructor
        super(context, attrs, defStyleAttr);

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

If it is written by kotlin, you only need to rewrite two constructor methods

	constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(
	) {

	@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
		context: Context?,
		attrs: AttributeSet?,
		defStyleAttr: Int,
		defStyleRes: Int
	) : super(context, attrs, defStyleAttr, defStyleRes) {

Three can then be rewritten as neededParent method

  1. View layout, callingonLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int)Method to ensure that the custom view is in the position of its parent view.
  2. View measurement, callingonMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)Method to determine the size of the view when drawing.
  3. View drawing, callingonDraw(canvas: Canvas)Method to draw the attribute information in the view to the screen.

If there is no problem with the above process, you can load the custom view like loading the system view. However, custom views often need to add some attribute controls. If you simply add some getter and setter methods to the view class to access relevant attributes, you can dynamically load custom views in the source code like using the system view. However, if you want to statically load the view in the layout file, you need to rewrite the three parameter construction method in the above code.
To set the property value statically, you must first create a fixed property nameres/valuesCreate a resource file in XML format in the resource directory and define attribute values in it, as shown below

Then, these attribute values can be obtained in the above rewriting construction method and given practical significance.

val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StyleMyEditText)
		val defaultText = typedArray.getString(R.styleable.StyleMyEditText_myDefaultText)
		Typedarray. Recycle() // the recycled code must not be less, otherwise it is easy to leak memory

In this way, the attribute value can be set normally in the layout file that statically loads the custom view.

Custom attribute values are used through the app field, and the Android field can only set fixed attribute values provided by the Android system

The content is limited, and the simple use of the view can be summarized first. For detailed cases, please refer to the subsequent video content. As the basic unit of interaction between the system and users, view has more diversified functions. The next chapter will continue to introduce the animation and interaction between views.

Recommended Today

Go reflection class instance

Internal mechanism of variables Type information: static meta information, predefined Value information: it is dynamically changed during program operation Use of reflection Get type information: reflect.typeof, which is static Get value information: reflect.valueof, which is dynamic Get interface value information by reflection package main import ( “fmt” “reflect” ) //Get interface value information by reflection […]