Basics of Android Development - Basic Usage of Activity

What is Activity

Activity is a component that can contain a user interface and is mainly used to interact with users.

An application can contain zero or more activities, but there are very few applications that do not contain any activities.

Basic usage of Activity

Manually create an Activity

Here select No Activity to create a new project, and name the project ActivityTest. At this time, you will find that the app\src\main\java\com\example\activitytest directory is empty, and then create a new Empty Activity under this package, and set It is named FirstActivity, and the Generate Layout File and Launcher Activity options are not checked, namely:

 The effects of the above two options are:

  • Generate Layout File: Check to indicate that a corresponding layout file will be automatically created for FirstActivity
  • Launcher Activity: Check to indicate that FirstActivity will be automatically set as the main Activity of the current project

At this point Android Studio will automatically generate the FirstActivity.kt file, its content is:

package com.example.activitytest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class FirstActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }
}

Any Activity in the project should rewrite the onCreate method, but the above onCreate is automatically generated. You can see that the above automatically generated onCreate method is very simple, which is to call the onCreate method of the parent class.

Create and load layouts

As mentioned before, Android program design pays attention to the separation of logic and view. It is best for each Activity to correspond to a layout.

The layout is used to display the interface content, here manually create a layout file.

Create a new directory under app\src\main\res, name it layout, and then create a new Layout resource file under layout, name it first_layout, and select LinearLayout as the root element by default:

 Then the following interface will appear:

 There are tabs for Design, Code and Split in the upper right corner of the picture above:

  • Design: Indicates the current visual layout editor. At this time, you can not only preview the current layout, but also edit the layout by dragging and dropping
  • Code: you can edit the layout through the XML file
  • Split: You can display both

Its XML file content is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

Before creating the layout file, LinearLayout was selected as the root element, so now there is a LinearLayout element in the layout file. Now add a button:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1"
    />

</LinearLayout>

A Button element is added above, and several attributes are added inside the Button element:

  • android:id: is to define a unique identifier for the current element, and then you can operate on the element in the code. This is exactly the usage of the XML file reference resource mentioned earlier, but one more + means to define an id
  • android:layout_width: specifies the width of the current element, match_parent means the same width as the parent element
  • android:layout_height: specifies the height of the current element, and wrap_content indicates that the height of the current element can just contain the content inside
  • android:text: Specifies the text content displayed in the element

As can be seen from the preview, the button has been added successfully, and then load the layout in the Activity:

package com.example.activitytest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class FirstActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_layout)
    }
}

 As you can see, the setContentView method is called here to load a layout for the current Activity, and an id generally needs to be passed in to this method. As mentioned before, any resource added to the project will generate a corresponding resource id in the R file, and the id of first_layout is passed in here.

Register in the AndroidManifest file

As mentioned before, all activities must be registered in AndroidManifest.xml to take effect. In fact, FirstActivity has been registered in AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.activitytest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ActivityTest">
        <activity
            android:name=".FirstActivity"
            android:exported="true" />
    </application>

</manifest>

 From the content of the above file, it can be seen that the registration statement of the Activity is located in the application tag. Here, the Activity is registered through the activity tag, but the registration process is automatically completed by Android Studio.

And in the activity tag:

  • android:name: specifies which Activity is specifically registered, where .FirstActivity is the abbreviation of com.example.activitytest.FirstActivity, because the package name com.example of the program has been specified through the package attribute in the outermost manifest tag. activitytest, so when registering Acitvity, this part can be omitted, directly use .FirstActivity

However, the above only registers the Activity, and the program still cannot run, because the main Activity has not been configured for the program, that is, when the program runs, it does not know which Activity to start first. The way to configure the main Activity is to add the following content inside the activity tag:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

In addition, you can also use android:label to specify the content of the title bar in the Activity, and the title bar is displayed at the top of the Activity. At the same time, the label specified for the main Activity will not only generate the content in the title bar, but also be called the name displayed by the application in the Launcher.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.activitytest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ActivityTest">
        <activity
            android:name=".FirstActivity"
            android:label="This is FirstActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            </activity>
    </application>

</manifest>

At this point, FirstActivity is called the main Activity of the program, which is the first activity that is opened when the desktop application icon is clicked. However, if the application does not declare any Activity as the main Activity, the program can still be installed normally, but it cannot be seen or opened in the launcher. Such programs are generally used as third-party services for other applications to use called internally.

The result of running the program at this time is:

Using Toast in Activity

Toast is a good reminder provided by the Android system. In the program, Toast can be used to notify the user of some short information, which will disappear automatically after a period of time and will not occupy any screen space.

First, you need to define a trigger point for popping up Toast. A button was defined before, and the click event of the button can be used as the trigger point for popping up Toast. At this point you need to add code in the onCreate method:

package com.example.activitytest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class FirstActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_layout)
        val button1: Button = findViewById<Button>(R.id.button1)
        button1.setOnClickListener {
            Toast.makeText(this, "You clicked Button 1.", Toast.LENGTH_SHORT).show()
        }
    }
}

 At this time, run the program and click BUTTON 1, the result is:

 In the Activity, the elements defined in the layout file are obtained through the findViewById method, and R.id.button1 is passed here to obtain the instance of the previously defined button. The findViewById method returns a generic object inherited from View, so Kotlin cannot automatically deduce whether it is a Button or other controls, so the button1 variable needs to be explicitly declared as the Button type.

After getting the instance of the button, register a listener for the button through the setOnClickListener method. When the button is clicked, the onClick method in the listener will be specified, so the function of popping up Toast is written in the onClick method.

Toast creates a Toast object through the static method makeText, and then calls the show method to display the Toast.

    public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
        return makeText(context, null, text, duration);
    }

At the same time, the makeText method needs three parameters. The first parameter is Context, which is the context required by Toast. Since Activity itself is a Context object, this can be passed in. The second parameter is the text content displayed by Toast, and the third parameter It is the duration displayed by Toast. There are two built-in constants to choose from: Toast.LENGTH_SHORT and Toast.LENGTH_LONG.

As for findViewById, this method can obtain the instance of the control in the layout file. In the previous example, there is only one button. If there are multiple controls in the layout file, the findViewById method needs to be called multiple times, which will be very cumbersome.

However, the kotlin-android-extensions plugin in Kotlin can automatically generate a variable with the same name according to the control id defined in the layout file, and the user can use the variable directly in the Activity without calling the findViewById method. Just need to add the plugin in the build.gradle file under app:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

 Then import the layout file in Activity:

import kotlinx.android.synthetic.main.first_layout.*

 At this point, the creation of the Button variable can be omitted, and the id of the Button can be directly used as the variable name:

package com.example.activitytest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import kotlinx.android.synthetic.main.first_layout.*

class FirstActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_layout)
//        val button1: Button = findViewById<Button>(R.id.button1)
        button1.setOnClickListener {
            Toast.makeText(this, "You clicked Button 1.", Toast.LENGTH_SHORT).show()
        }
    }
}

At the same time, this is also the recommended way of writing in Kotlin.

Use Menu in Activity

The screen space of the mobile phone is limited, so it is necessary to make full use of the screen space for display, and if there are a large number of menus to be displayed, the interface design will be more troublesome, and Android provides a way to allow the menus to be displayed. Take up screen real estate.

Create a new folder in the res directory, and name it menu, then create a Menu resource file in this directory, and name it main, add the following code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/add_item"
        android:title="Add"/>
    <item
        android:id="@+id/remove_item"
        android:title="Remove"/>
</menu>

The code above creates two menu items:

  • item: This tag is used to create a specific menu item
  • android:id: used to specify a unique identifier for the menu item
  • android:title: used to specify a name for the menu

Then override the onCreateOptionsMenu method in FirstActivity:

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.main, menu)
    return true
}

In this code, menuInflater actually calls the getMenuInflater method of the parent class, which can get a MenuInflater object, and then call its inflate method to create a menu for the current Activity.

The inflate method receives two parameters. The first parameter is used to specify which resource file to create the menu. Here, R.menu.main is passed in. The second parameter is used to specify the Menu object to which the menu item will be added. Here Directly use the menu parameter passed in the onCreateOptionsMenu method. Finally, it returns true, which means that the created menu is allowed to be displayed. If it returns false, the created menu will not be displayed.


    /**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *            <code>R.menu.main_activity</code>)
     * @param menu The Menu to inflate into. The items and submenus will be
     *            added to this Menu.
     */
    public void inflate(@MenuRes int menuRes, Menu menu)

After the menu can be displayed, it is necessary to define the menu response event. Rewrite the onOptionsItemSelected method in FirstActivity:

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.add_item -> Toast.makeText(this, "You clicked Add", Toast.LENGTH_SHORT).show()
            R.id.remove_item -> Toast.makeText(this, "You clicked Remove", Toast.LENGTH_SHORT).show()
        }
        return true
    }

 In the onOptionsItemSelected method, the item.itemId is called to determine which menu item is clicked. In fact, the getItemId method of the item is called here. This concise writing method is actually Kotlin's syntactic sugar. Then use the when conditional statement for logic processing.

The result of running the above code is:

 Destroy an Activity

What I mentioned before is the operation of creating an Activity and adding content to the Activity, but how to destroy the Activity?

In fact, the current Activity can be destroyed simply by pressing the back button, and if you don’t want to press the button, you can also destroy it by code, that is, call the finish method. For example, modify the trigger code of the button:

        button1.setOnClickListener {
//            Toast.makeText(this, "You clicked Button 1.", Toast.LENGTH_SHORT).show()
            finish()
        }

Clicking the button at this time will exit the current Activity, and the effect is the same as the back button.

Guess you like

Origin blog.csdn.net/SAKURASANN/article/details/126806992