Article directory
- 1. Learning objectives
- 2. Learning new lessons
-
- (1) Three basic controls
- (2) Android event processing mechanism
- (3) Case Demonstration: Implementing User Login
-
- 1. Create an Android application
- 2. Prepare background image
- 3. Create a login window based on the template
- 4. Login window layout resource file
- 5. Main window layout resource file
- 6. Android project manifest file
- 7. String resource file
- 8. Implementation of login window function
- 9. Start the application and check the effect
- (4) Using intent to launch components
- (5) Use intent to transfer data
- (6) Case demonstration: Modify user login program
1. Learning objectives
- Master event handling
- Understanding intentIntent
- Master window jumps and transfer data
2. Learning new lessons
- Android applications often have multiple activities. How to jump from one activity to another? Event processing is often required, and a very important component in Android is also used - Intent, which can be regarded as a bridge between different components of Android.
(1) Three basic controls
1. Label control (TextView)
- Class hierarchy inheritance diagram
Attributes | meaning |
---|---|
text | text content |
textSize | Text size |
textColor | Text color, unit: sp |
layout_height | Height, unit: dp (wrap_content, match_parent) |
layout_width | Width, unit: dp (wrap_content, match_parent) |
2. Edit box control (EditText)
-
Class hierarchy inheritance diagram
-
Common properties
Attributes | meaning |
---|---|
text | text content |
textSize | Text size |
textColor | Text color, #ff0000 - red |
hint | Prompt message |
singleLine | Single line (true or false) |
layout_height | Height, unit: dp (wrap_content, match_parent) |
layout_weight | Width, unit: dp (wrap_content, match_parent) |
inputType | Input type (plain text, password, email...) |
3. Button control (Button)
-
Class hierarchy inheritance diagram
-
Common properties
Attributes | meaning |
---|---|
text | text content |
textSize | Text size |
textColor | Text color, #ff0000 - red |
background | Background color or background image |
layout_height | Height, unit: dp (wrap_content, match_parent) |
layout_weight | Width, unit: dp (wrap_content, match_parent) |
- EditText and Button are brothers, their father is TextView
(2) Android event processing mechanism
1. Overview of Android event processing
- Whether it is a desktop application or a mobile application, it needs to provide responses to user actions. This mechanism for providing responses to user actions is event processing.
- Android provides two event processing mechanisms: callback-based event processing and listener-based event processing.
- Listening-based event processing is a kind of "object-oriented" event processing, involving three types of objects: event source (EventSource), event (Event), and event listener (EventListener).
- Monitoring-based event processing flow chart
2. Android event processing steps
- Taking button click event processing as an example to illustrate the Android event processing steps
serial number | Task |
---|---|
1 | Declare button control variables in the interface class |
2 | Get the button instance through the findViewById() method |
3 | Use the setOnClickListener() method to register a click event listener for the button |
4 | Implement the click event listener interface, using anonymous implementation |
5 | Write event handling code in the abstract method of the interface |
(3) Case Demonstration: Implementing User Login
1. Create an Android application
-
Empty Activity
Create Android apps based on templates
-
Configure project information
-
Click the [Finish] button
2. Prepare background image
- Copy background image
background.png
todrawable
directory
3. Create a login window based on the template
-
Create LoginActivity based on the Empty Activity template, generate the corresponding layout file, and set it to start the Activity
-
Click the [Finish] button
4. Login window layout resource file
-
Login window layout resource file -
activity_login.xml
-
Change constraint layout to linear layout and set related properties
-
Add user login label
-
Add a label and edit box for entering the user name, but need a horizontal linear layout to frame them
-
Add labels and edit boxes for entering passwords, but need a horizontal linear layout to frame them
-
Add a login button and a cancel button, but need a horizontal linear layout to frame them
-
Complete code of login window layout resource file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:gravity="center"
android:orientation="vertical"
android:padding="15dp"
tools:context=".LoginActivity">
<TextView
android:id="@+id/tv_user_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/user_login"
android:textColor="#0000ff"
android:textSize="25sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/username"
android:textColor="#000000"
android:textSize="20sp" />
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="56dp"
android:hint="@string/input_username"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/password"
android:textColor="#000000"
android:textSize="20sp" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/input_password"
android:inputType="textPassword"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="@string/login"
android:textSize="20sp" />
<Button
android:id="@+id/btn_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="@string/cancel"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
Attributes | effect |
---|---|
gravity | Used to set the alignment of the child controls of the container, or the alignment of the content of the control |
orientation | The direction of linear layout (horizontal - horizontal, vertical - vertical) |
padding | Padding, used to set the distance between the child control and the border of the parent container, or the distance between the content of the control and the border of the control; (paddingLeft, paddingRight, paddingTop, paddingBottom) |
layout_margin | Margins, used to set the distance between controls; (layout_marginLeft, layout_marginRight, layout_marginTop, layout_marginBottom) |
5. Main window layout resource file
- Main window layout resource file -
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="25dp"
android:textColor="#0000ff"
/>
</LinearLayout>
6. Android project manifest file
- Android project manifest file AndroidManifest.xml, delete the intent filter contained in the MainActivity element
7. String resource file
- Define the required string variables in the string resource file strings.xml
<resources>
<string name="app_name">系统登录</string>
<string name="user_login">用户登录</string>
<string name="username">用户:</string>
<string name="input_username">请输入用户名</string>
<string name="password">密码:</string>
<string name="input_password">请输入密码</string>
<string name="login">登录</string>
<string name="cancel">取消</string>
</resources>
8. Implementation of login window function
- Login window -
LoginActivity
(1) Declare control variables
- Two edit box variables and two button variables
(2) Obtain the control instance through the resource identifier
- Get the control instance through
findViewById()
the method (similar to the method in JavaScriptgetElementById()
)
(3) Login button event processing
- Register a click listener for the login button, implement the listener interface, and write event processing code
- First, get the username and password entered by the user, then determine whether they are correct and pop up different toasts.
(4) Cancel button event processing
-
Register a click listener for the cancel button, implement the listener interface, and write event handling code
-
Click the Cancel button to close the login window (there is another way to do it, just clear the two edit boxes without closing the window)
-
complete code
package net.xqf.user_login;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnCancel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 利用布局资源文件设置用户界面
setContentView(R.layout.activity_login);
// 通过资源标识符获取控件实例
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
btnLogin = findViewById(R.id.btn_login);
btnCancel = findViewById(R.id.btn_cancel);
// 给登录按钮注册单击监听器,实现监听器接口,并且编写事件处理代码
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 获取两个编辑框的数据(trim()方法用于去除字符串前后空格)
String strUsername = etUsername.getText().toString().trim();
String strPassword = etPassword.getText().toString().trim();
// 判断用户名与密码是否正确(假定用户名是"howard",密码是"903213")
if (strUsername.equals("howard") && strPassword.equals("903213")) {
// 三个参数:参数1 - 上下文;参数2:吐司内容(字符串);参数3:吐司持续时间
Toast.makeText(LoginActivity.this, "恭喜,用户名和密码正确!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "遗憾,用户名或密码错误!", Toast.LENGTH_SHORT).show();
}
}
});
// 给取消按钮注册单击监听器,实现监听器接口,并且编写事件处理代码
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 关闭当前窗口
finish();
}
});
}
}
9. Start the application and check the effect
- Thinking: If you want the user login label to be separated from the input user name edit below, how should you set the properties of the label?
(1) Enter the username and password correctly
- Username: xiao
- Password: 123456
(2) If the user name or password is entered incorrectly
-
Username: papsp
-
Password: 987654
-
You can specify the width of the two edit boxes, such as 200dp
-
Restart the app and see the effect
(4) Using intent to launch components
1. Use explicit intent to launch components
- Suppose there are two windows: FirstActivity and SecondActivity
method one
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
Method 2
Intent intent = new Intent();
intent.setClass(FirstActivity.this, SecondActivity.class);
startActivity(intent);
Method three
Intent intent = new Intent();
ComponentName component = new ComponentName(FirstActivity.this, SecondActivity.class);
intent.setComponent(component);
startActivity(intent);
2. Use implicit intent to launch components
(1) Create implicit intentions in Java code
Intent intent = new Intent();
intent.setAction("net.hw.ACTION_NEXT");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
(2) Set intent filters in the project manifest file
<activity android:name="net.hw.SecondActivity">
<intent-filter>
<action android:name="net.hw.ACTION_NEXT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
(5) Use intent to transfer data
1. Transfer single item of data
- Pass single item data through intent in the starting component
// 通过意图传递单项数据
intent.putExtra("username", strUsername);
intent.putExtra("password", strPassword);
Obtain single item data through intent in the target component
// 通过意图获取单项数据
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
2. Deliver data packets
(1) Carrying data packets through intent in the initial component
// 创建数据包,封装数据
Bundle data = new Bundle();
data.putString("username", strUsername);
data.putString("password", strPassword);
// 通过意图携带数据包
intent.putExtras(data);
(2) Get the data packet through the intent in the target component
// 获取意图携带的数据包
Bundle data = intent.getExtras();
// 从数据包里按键取值获取各项数据
String username = data.getString("username");
String password = data.getString("password");
(6) Case demonstration: Modify user login program
- Functional requirements: When the login is successful, jump to the main window and display the user name and password.
1. Modify the login window code
- Create explicit intents, use intents to carry data, and launch target components according to intents
// 创建显式意图(参数1 - 包上下文;参数2 - 目标组件)
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// 通过意图携带数据
intent.putExtra("username", strUsername);
intent.putExtra("password", strPassword);
// 按照意图启动目标组件
startActivity(intent);
2. Modify the main window code
- Receive the data passed by the login window through the intent and display it in the label
package net.hw.user_login;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tvMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 利用布局资源文件设置用户界面
setContentView(R.layout.activity_main);
// 通过资源标识符获取控件实例
tvMessage = findViewById(R.id.tv_message);
// 获取意图
Intent intent = getIntent();
// 判断意图是否为空
if (intent != null) {
// 获取意图携带的数据
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
// 拼接用户信息
String message = "登录成功!\n用户:" + username + "\n密码:" + password;
// 设置标签属性,显示用户信息
tvMessage.setText(message);
}
}
}
3. Start the application and check the effect
(1) Enter the username and password correctly
-
Username: xiao
-
Password: 123456
-
Click the [Login] button
(2) If the user name or password is entered incorrectly
- Username: hhh
- Password: 987654
4. Modify the login window code
- Encapsulate multiple pieces of data into data packets and deliver the data packets through intent
5. Modify the main window function code
- Obtain the data packet through the intention, and then obtain various data from the data packet by pressing the key
6. Start the application and test the effect
- Login operation screen recording