Basic usage of activities

1. Introduction of activities and various documents

First, let's briefly introduce what an activity is?
An activity is a component that can contain a user interface, mainly interacting with the user on a mobile phone.

Then, let's talk about how to create an activity with Android Studio.
Click on Start a new Android Studio project

Select Empty Activity under Phone and Tablet

Then, enter your project name, here I enter FirstActivity, Save location choose the local location where you want to put the project, Language choose Java, you can choose the API that is different from mine, but I recommend choosing a version that is not too low Bar. If the API is too low, it may cause the new mobile phones to not run.

Here we briefly talk about a few files that are often used to learn the basics of Android. (It doesn't matter if you don't understand, it will be used later)
(1) The first is the AndroidManifest.xml file in the app/manifests folder, which is mainly used to register activities, services, broadcasts, etc.
(2) Then there is the file MainActivity in the com.example.firstactivity directory under java, which is the file automatically generated by the Empty Activity we just created. It is also the activity that the system sets you to open first when you open the app. This directory will also be used to create various required classes.
(3) Then there are the various folders in the res directory, in simple terms,
I am used to putting pictures in the drawable folder, layout files in the layout folder, and values ​​in various styles and string explanations.

There are also files in this elephant. The second build.gradle is mainly used to add dependencies, which will be used in subsequent projects.

2. Code combat

First, we modify the activity_main.xml file under the layout as follows:

2.1 Set the interface layout

<?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/button_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button1"/>
</LinearLayout>

A LinearLayout layout is set up here (will be explained later, let's not talk about it first), and then a button is placed in the layout.
android:id defines a unique identifier for the current element.
android:layout_width is the width of the control, set to match_parent is the same as its parent layout, where the parent layout is LinearLayout, and its size matches the size of the entire phone.
android:layout_height is the height of this control. Setting it to wrap_content is the same as its content. If you write enough, it may hold a few more lines.
android:text is the content of this control.

2.2 Add the layout to the activity

Next, let's look at the MainActivity file, the code is as follows:

package com.example.firstactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

I don't need to worry about many here. I will explain the last sentence of setContentView, which is to specify the layout of the activity. If you have written other layout files, you can also use this method to specify that the activity points to other layout files.
R.layout.activity_main
Interpret it in my meaning: R specifies the res folder, then layout is the layout folder under res, and activity_main is the activity_main.java file under him.

2.3 Registration Activities

Then we look at the AndroidManifest.xml file:

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

    <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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Here, the system automatically generates

<activity android:name=".MainActivity>
.....
.....
</activity>

It has been automatically generated and registered the MainActivity activity for us.

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

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

The two lines action and category set it as the main activity, and set it to be called when the app is launched.

2.4 Running results


At this time, the button has not listened to the event, and there is no response after clicking.

2.5 Using Toast in Activities

Next, let's briefly talk about how to instantiate the button and set its listener events.
We go back to the MainActivity.java file, the code is as follows:

package com.example.firstactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity 
		implements View.OnClickListener {
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init(){
        button = (Button) findViewById(R.id.button_1);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_1:
                Toast.makeText(this, "You clicked the button_1",
                        Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }
}

Here, let me talk about it. My habit is to define controls such as buttons as active private variables, and then use an init() method to instantiate all controls and set up listeners.
Then let the activity implement the View.OnClickListener interface and implement its onClick() method.

Detailed explanation:
In the init() method, we use the findViewById() method to instantiate the button. The point to note here is that what type of control is this control, then findViewById must be forced to be converted to what type.

R.id.button_1 is actually the id of the Button we just set in the layout file of activity_main.xml. It is nothing more than to tell him that this id is defined in the res directory, and his id is called button_1.
setOnClickListener sets his listener, here because we have implemented View.OnClickedListener, we can directly set it to this.

onClick is a listener function that is automatically called. We can know his Id through v.getId(), and then use switch to operate the control corresponding to the id.
Here we simply use a Toast, call its makeText method, the first parameter is Context, which is the context required by Toast, here is the object of MainActivity, which is this, and the second is the content displayed by Toast , the third is the display time, here we set a short time display. Then use show() to display it.

2.6 Running results

When you click the button BUTTON1, you can see that a prompt appears below, saying You Clicked the button_1 (in fact, it is the content to be displayed by the Toast we set.)

Tags: Android

Posted by rocram16 on Tue, 03 May 2022 16:41:17 +0300