Android中的Activity(案例+代码+效果图)

目录

1.Activity的生命周期

核心生命周期回调

1)onCreate()

2)onStart()

3)onResume()

4)onPause()

5)onStop()

6)onRestart()

7)onDestroy()

8)生命周期图示

10)注意事项

2.如何创建一个Activity

3.清单文件配置Activity  (AndroidManifest.xml)

1)第一种配置

2)第二种配置

4.如何启动和关闭

1)启动

2)关闭

3.Intent与IntentFilter

1)Intent

1-主要用途

2-创建 Intent

3-添加额外数据

4-接收额外数据

2)IntentFilter

1-声明方式

2-组成部分

1--Action

2--Category

3--Data

3-匹配规则

1--Action

2--Category

3--Data

4.Activity之间的传递

1)数据传递

1-通过putExtra()方法传递

1--数据的传递

2--数据的接受

2-通过通过Bundle类传递数据

1--数据发送

2--数据接受

2)数据回传

1. startActivityForResult()方法 (activity销毁时,返回数据)

2.setResult()方法

3.onActivityResult()

案例:模拟登录修改

1.代码

1--xml代码

1---activity_main.xml代码

2---activity_login_main.xml代码

3---activity_alter_info.xml代码

4.AndroidManifest.xml

2--java代码

1---MainActivity

2---LoginInfo

3---AlterInfo

2.效果


1.Activity的生命周期

核心生命周期回调

1)onCreate()

  • 当 Activity 被创建时调用
  • 这是初始化组件的最佳时机,比如设置布局、绑定数据等。
  • 示例代码:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化其他组件...
    }

2)onStart()

  • 当 Activity 变得可见但尚未获取焦点时调用。
  • 在这个阶段,用户到 Activity,但是还不能与之交互

3)onResume()

  • 当 Activity 开始与用户交互并获得焦点时调用
  • 此时 Activity 处于活动状态,并可以响应用户的输入。

示例代码:

@Override
protected void onResume() {
    super.onResume();
    // 恢复暂停的操作,如开始传感器监听...
}

4)onPause()

  • 当 Activity 部分被遮挡或完全不可见时调用。
  • 系统可能会在 Activity 不再处于前台时调用此方法,例如当新的 Activity 启动或者对话框出现时。
  • 在这里应该释放一些资源以提高系统性能。
  • 示例代码:
@Override
protected void onPause() {
    super.onPause();
    // 停止占用CPU的动画或其他操作...
}

5)onStop()

  • 当 Activity 对用户完全不可见时调用。
  • 在这个阶段,Activity 已经不再显示给用户,但仍驻留在内存中
  • 示例代码:
@Override
protected void onStop() {
    super.onStop();
    // 更多清理工作...
}

6)onRestart()

  • 当 Activity 从停止状态动时调用
  • 它总是在 onStart() 方法之前调用。
  • 示例代码:
@Override
protected void onRestart() {
    super.onRestart();
    // 重启时的处理逻辑...
}

7)onDestroy()

  • 当 Activity 即将被销毁时调用
  • 在这里进行最后的清理工作,比如取消网络请求、关闭数据库连接等。
  • 示例代码:
@Override
protected void onDestroy() {
    super.onDestroy();
    // 清理所有剩余资源...
}

8)生命周期图示

+---------------------+
|      onCreate()     |
+---------------------+
          |
          v
+---------------------+
|      onStart()      |
+---------------------+
          |
          v
+---------------------+
|     onResume()      |
+---------------------+
          |
          v
+---------------------+  +---------------------+
|                      |  |    用户交互...     |
|    Activity活跃      |<->|                    |
|                      |  |                    |
+---------------------+  +---------------------+
          |
          v
+---------------------+
|     onPause()       |
+---------------------+
          |
          v
+---------------------+
|      onStop()       |
+---------------------+
          |
          v
+---------------------+
|      onDestroy()    |
+---------------------+

10)注意事项

  • onSaveInstanceState(Bundle outState) 和 onRestoreInstanceState(Bundle savedInstanceState) 是用于保存和恢复 Activity 状态的方法,它们通常在配置更改(如屏幕旋转)或低内存情况下的进程被杀死后重新创建 Activity 时使用。
  • 如果你在 AndroidManifest.xml 中为 Activity 设置了 android:configChanges 属性,那么系统会在配置改变时不会自动销毁并重建 Activity,而是会调用 onConfigurationChanged(Configuration newConfig) 方法。
  • 在处理 Activity 生命周期时,要确保你的应用能够优雅地处理各种可能的情况,包括突然的中断和意外的退出。

2.如何创建一个Activity

在res的目录 === > 鼠标右击  ===》 new   ===> Activity   ===>Empty Views Activity

手动创建一个AlterInfo

3.清单文件配置Activity  (AndroidManifest.xml

1)第一种配置

        <!--配置LoginInfo-->
        <activity
            android:name=".LoginInfo"
            android:exported="false" />

2)第二种配置

注:类名大写+

        <!--配置隐式意图-->
        <activity
            android:name=".AlterInfo"
            android:exported="true">
            
            <intent-filter>
                <action android:name="com.xiji.myapplication123.ALTER_INFO" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

清单文件所有内容

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication123"
        tools:targetApi="31">

        <!--配置LoginInfo-->
        <activity
            android:name=".LoginInfo"
            android:exported="false" />

        <!---->
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!--配置隐式意图-->
        <activity
            android:name=".AlterInfo"
            android:exported="true">
            
            <intent-filter>
                <action android:name="com.xiji.myapplication123.ALTER_INFO" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4.如何启动和关闭

1)启动

public void startActivity (Intent intent);

//创建意图,并且指定要跳转的页面

Intent intent = new Intent(MainActivity.this,LoginInfo.class);

//启动

startActivity(intent);

2)关闭

public void finsh();

控件.设置监听事件((){

        public void 事件{

                 finsh();//调用finsh()关闭就可以了

        

        }

});

3.Intent与IntentFilter

1)Intent

  Intent 是一种消息对象,它可以在不同组件之间发送,以执行特定的动作。它可以携带数据,并且可以指定要执行的操作的类型、目标组件以及一些额外的数据。

1-主要用途
  • 启动 Activity:使用 startActivity(Intent) 方法。
  • 启动 Service:使用 startService(Intent) 方法。
  • 发送广播:使用 sendBroadcast(Intent)sendOrderedBroadcast(Intent, String), 等方法。
2-创建 Intent
// 显式 Intent - 直接指定目标组件
Intent explicitIntent = new Intent(context, TargetActivity.class);

// 隐式 Intent - 通过 Action 和 Category 来匹配合适的组件
Intent implicitIntent = new Intent();
implicitIntent.setAction(Intent.ACTION_VIEW);
implicitIntent.setData(Uri.parse("http://www.example.com"));
3-添加额外数据
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("key", "value");
startActivity(intent);
4-接收额外数据
Intent intent = getIntent();
String value = intent.getStringExtra("key");

2)IntentFilter

IntentFilter 用来定义一个组件愿意接收哪种类型的 Intent。它通常在 AndroidManifest.xml 文件中与组件一起声明,或者在代码中动态创建。

1-声明方式
  • 在 Manifest 文件中声明

    <activity android:name=".TargetActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="http" />
        </intent-filter>
    </activity>
  • 在代码中动态创建

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.example.MY_ACTION");
    registerReceiver(myBroadcastReceiver, filter);
2-组成部分
1--Action

        表示 Intent 的动作,例如 ACTION_VIEWACTION_SEND 等。

2--Category

        提供 Intent 的附加信息,比如 CATEGORY_DEFAULTCATEGORY_BROWSABLE 等。

3--Data

        指定 Intent 操作的数据和数据类型,例如 URI 和 MIME 类型。

3-匹配规则

当系统尝试找到能够响应给定 Intent 的组件时,会根据 IntentIntentFilter 的以下属性进行匹配:

1--Action

  Intent 的 action 必须与 IntentFilter 中的一个 action 匹配。

2--Category

  Intent 中的所有 category 都必须在 IntentFilter 中出现。

3--Data

      如果 Intent 包含 data,那么 data 必须与 IntentFilter 中的一个 data 规范匹配。

4.Activity之间的传递

1)数据传递

1-通过putExtra()方法传递

1--数据的传递

Intent intent = new Intent();

//页面跳转

intent.setClass(MainActivity.this,LoginInfo.calss)

//要传递的数据

intent.putExtra("键名","数据");

2--数据的接受

Intent intent = getIntent();

//通过键名获取
intent.getStringExtra("键名")

2-通过通过Bundle类传递数据

1--数据发送

Intent intent = new Intent();

//设置跳转的

intent.setClass(this,LoginInfo.class);

//创建并且封装Bundle类

Bundle bundle = new Bundle();

bundle.putString("键名","键值")

intent.putString(bundle);

startActivity(intent);

2--数据接受

//获取bundle对象

Bundle bundle = getIntent().getExtras();

//通过键名取

String 名字 = bundle.getString("键名")

2)数据回传

1. startActivityForResult()方法 (activity销毁时,返回数据)

startActivityForResult(Intent 意图, int 结果响应码);

2.setResult()方法

setResult(int 结果响应码,Intent 意图)

3.onActivityResult()

接受回传数据

重写回传Activity页面的的onActivityResult()方法;

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

案例:模拟登录修改

流程图:

1.代码

1--xml代码

1---activity_main.xml代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"


        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="用户登录"
            android:gravity="center"
            android:textSize="20sp"
            android:textColor="#F6F6F6"
            tools:ignore="MissingConstraints"
            android:background="#46E90B"
            android:padding="20sp"
            />

        <!--用户框-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_marginTop="60dp"
        >
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用户名"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="77dp"
            tools:layout_editor_absoluteY="149dp" />


        <EditText
            android:id="@+id/editName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="输入用户名"
            android:inputType="text"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="145dp"
            tools:layout_editor_absoluteY="136dp" />


    </LinearLayout>
<!--密码框-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"

        >


        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密 码"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="77dp"
            tools:layout_editor_absoluteY="222dp" />

        <EditText
            android:id="@+id/editPassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="请输入用户密码"
            android:inputType="textPassword"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="145dp"
            tools:layout_editor_absoluteY="208dp" />

    </LinearLayout>

        <!--登录按钮-->
        <Button
            android:id="@+id/loginButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#1781EB"
            android:text="登录"
            android:theme="@style/Theme.Design.NoActionBar"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="145dp"
            tools:layout_editor_absoluteY="378dp"
            android:layout_gravity="center"
            />

    </LinearLayout>








</androidx.constraintlayout.widget.ConstraintLayout>

2---activity_login_main.xml代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginInfo">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"


        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="用户信息"
            android:gravity="center"
            android:textSize="20sp"
            android:textColor="#F6F6F6"
            tools:ignore="MissingConstraints"
            android:background="#02D8F4"
            android:padding="20sp"
            />

        <!--中间布局-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_marginTop="60dp"
        >
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用户名"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="77dp"
            tools:layout_editor_absoluteY="149dp" />


        <EditText
            android:id="@+id/editNameInput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="用户名"
            android:inputType="text"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="145dp"
            tools:layout_editor_absoluteY="136dp"
            android:enabled="false"
            />

    </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center"

            >
            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密 码"
                tools:ignore="MissingConstraints"
                tools:layout_editor_absoluteX="77dp"
                tools:layout_editor_absoluteY="222dp" />
            <EditText
                android:id="@+id/editPasswordInput"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="密码"
                android:inputType="textPassword"
                tools:ignore="MissingConstraints"
                tools:layout_editor_absoluteX="145dp"
                tools:layout_editor_absoluteY="208dp"
                android:enabled="false"
                />

        </LinearLayout>



        <Button
            android:id="@+id/loginAlterButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#1781EB"
            android:text="修改"
            android:theme="@style/Theme.Design.NoActionBar"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="145dp"
            tools:layout_editor_absoluteY="378dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:layout_marginTop="200dp"
            />


    </LinearLayout>









</androidx.constraintlayout.widget.ConstraintLayout>

3---activity_alter_info.xml代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AlterInfo">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"


        android:orientation="vertical"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="用户信息修改"
            android:gravity="center"
            android:textSize="20sp"
            android:textColor="#F6F6F6"
            tools:ignore="MissingConstraints"
            android:background="#E9D30B"
            android:padding="20sp"


            />

        <!--控件-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center"
            android:layout_marginTop="60dp"
            >
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="用户名"
                tools:ignore="MissingConstraints"
                tools:layout_editor_absoluteX="77dp"
                tools:layout_editor_absoluteY="149dp" />

            <EditText
                android:id="@+id/editAlterNameInput"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="用户名"
                android:inputType="text"
                tools:ignore="MissingConstraints"
                tools:layout_editor_absoluteX="145dp"
                tools:layout_editor_absoluteY="136dp"
                android:enabled="true"
                />

        </LinearLayout>
        <!--控件-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center"
            >
            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密 码"
                tools:ignore="MissingConstraints"
                tools:layout_editor_absoluteX="77dp"
                tools:layout_editor_absoluteY="222dp" />
            <EditText
                android:id="@+id/editAlterPasswordInput"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="密码"
                android:inputType="text"
                tools:ignore="MissingConstraints"
                tools:layout_editor_absoluteX="145dp"
                tools:layout_editor_absoluteY="208dp"
                android:enabled="true"
                />


        </LinearLayout>

        <Button
            android:id="@+id/loginAlterButtonInfo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#1781EB"
            android:text="点击修改"
            android:theme="@style/Theme.Design.NoActionBar"
            tools:ignore="MissingConstraints"
            tools:layout_editor_absoluteX="145dp"
            tools:layout_editor_absoluteY="378dp"
            android:layout_marginTop="50dp"
            android:layout_gravity="center"
            />


    </LinearLayout>










</androidx.constraintlayout.widget.ConstraintLayout>

4.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication123"
        tools:targetApi="31">

        <!--配置LoginInfo-->
        <activity
            android:name=".LoginInfo"
            android:exported="false" />

        <!---->
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!--配置隐式意图-->
        <activity
            android:name=".AlterInfo"
            android:exported="true">

            <!--这里面的活动名字要和action名字一样-->
            <intent-filter>
                <action android:name="com.xiji.myapplication123.ALTER_INFO" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

2--java代码

1---MainActivity
package com.xiji.myapplication123;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    //获取控件
    private EditText username;
    private EditText password;
    private Button loginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //控件初始化
        initView();
        //事件绑定
        initListener();
    }

    //控件初始化
    private void initView() {
        username = findViewById(R.id.editName);
        password = findViewById(R.id.editPassword);
        loginButton = findViewById(R.id.loginButton);
    }

    //事件绑定
    private void initListener() {
        loginButton.setOnClickListener(v -> {
            String user = username.getText().toString();
            String pwd = password.getText().toString();

            //显示意图
            Intent intent = new Intent(MainActivity.this, LoginInfo.class);
            //传递输入的数据
            if (user.equals("") || pwd.equals("")) {
                Toast.makeText(MainActivity.this, "账户和密码不能为空", Toast.LENGTH_SHORT);
                return;
            }
            intent.putExtra("username", user);
            intent.putExtra("password", pwd);

            startActivity(intent);
            Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
        });
    }
}

2---LoginInfo
package com.xiji.myapplication123;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class LoginInfo extends AppCompatActivity {

    //获取展示控件,并且把信息展示
    private EditText username;
    private EditText password;
    //修改按钮
    private Button alterButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login_info);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //控件初始化
        initView();
        //监听初始化
        initListener();
        //初始化数据
        initData();
    }

    //控件初始化
    private void initView(){
        username = findViewById(R.id.editNameInput);
        password = findViewById(R.id.editPasswordInput);
        alterButton = findViewById(R.id.loginAlterButton);
    }

    private void initListener(){
        alterButton.setOnClickListener(v -> {

            //Bundle传递信息
            Bundle bundle = new Bundle();

            //创建意图
            Intent intent = new Intent();

            //隐式传递
            intent.setClass(this, AlterInfo.class);
            intent.setAction("com.xiji.myapplication123.ALTER_INFO");
            //传递数据
            bundle.putString("username", username.getText().toString());
            bundle.putString("password", password.getText().toString());
            intent.putExtras(bundle);
            //启动


            //发送请求  如果要获取返回结果,必须要带请求码
            startActivityForResult(intent, 100);


        });
    }

    /***
     * 接受数据,数据传递
     */
    private void initData(){
        Intent intent = getIntent();
        if(intent != null){
            Bundle bundle = intent.getExtras();
            username.setText(bundle.getString("username"));
            password.setText(bundle.getString("password"));

        }
        Toast.makeText(this, "数据已接收", Toast.LENGTH_SHORT);
    }

    /**
     * 数据回传监听
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("接受回传"+data);
        Toast.makeText(this, "接受回传", Toast.LENGTH_SHORT);

        //根据返回码不同做出不同的效果
        //接受请求
        if (resultCode == 200 && requestCode == 100) {

            //获取Bundle数据
            Bundle bundle = data.getExtras();

            //修改成功
            username.setText(bundle.getString("username"));
            password.setText(bundle.getString("password"));
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT);

            return;
        }
        //修改失败
        Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT);

    }
}

3---AlterInfo
package com.xiji.myapplication123;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class AlterInfo extends AppCompatActivity {

    //控件初始化
    private EditText alter_name;
    private EditText alter_password;
    //按钮
    private Button alter_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_alter_info);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //控件初始化
        initView();
        //事件绑定
        initListener();

        //获取数据
        initData();
    }
    //控件初始化
    private void initView(){
        alter_name = findViewById(R.id.editAlterNameInput);
        alter_password = findViewById(R.id.editAlterPasswordInput);
        alter_button = findViewById(R.id.loginAlterButtonInfo);
    }

    //按钮监听并且回传
    private void initListener(){

        alter_button.setOnClickListener(v -> {
            //回传数据
            Bundle bundle = new Bundle();
            bundle.putString("username", alter_name.getText().toString());
            bundle.putString("password", alter_password.getText().toString());


            //设置回传数据


            //通过意图返回
            Intent intent = new Intent(AlterInfo.this, LoginInfo.class);

            intent.putExtras(bundle);
            setResult(200, intent);

            Toast.makeText(this, "userName:: "+alter_name.getText().toString()+"\npassword::"+alter_password.getText().toString(), Toast.LENGTH_SHORT).show();
            //数据销毁
            finish();
        });
    }

    //获取数据接受
    public void initData(){

        Intent intent = getIntent();
        if(intent != null){
            Bundle bundle = intent.getExtras();
            alter_name.setText(bundle.getString("username"));
            alter_password.setText(bundle.getString("password"));
        }
    }
}

2.效果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/890435.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Golang | Leetcode Golang题解之第468题验证IP地址

题目&#xff1a; 题解&#xff1a; func validIPAddress(queryIP string) string {if sp : strings.Split(queryIP, "."); len(sp) 4 {for _, s : range sp {if len(s) > 1 && s[0] 0 {return "Neither"}if v, err : strconv.Atoi(s); err …

教你把产品图册转为翻页电子书

​在科技飞速发展的今天&#xff0c;产品的宣传方式也在不断创新。为了让产品图册更加吸引眼球&#xff0c;我推出了一款结合动画和音乐的效果惊艳的产品图册。这款产品图册不仅展示了产品的精美外观和独特功能&#xff0c;更通过动态效果和美妙音乐&#xff0c;为观众带来一场…

LabVIEW提高开发效率技巧----点阵图(XY Graph)

在LabVIEW开发中&#xff0c;点阵图&#xff08;XY Graph&#xff09; 是一种强大的工具&#xff0c;尤其适用于需要实时展示大量数据的场景。通过使用点阵图&#xff0c;开发人员能够将实时数据可视化&#xff0c;帮助用户更直观地分析数据变化。 1. 点阵图的优势 点阵图&…

【puppeteer】wvp-puppeteer制作 过程

目录 最后的结论 制作windows&ubuntu的docker 重启桌面上的docker 命令重启 通过 Docker Desktop 图形界面重启 制作centos docker 测试 参考文档 最后的结论 ubuntu && windows 使用 dualvenregistry:5000/wvp-puppeteer:1.0 centos7 使用&#xff1a;…

Word 中脚注和尾注的区别有哪些?如何正确使用它们?

在撰写学术论文、报告或其他需要引用资料的文章时&#xff0c;脚注和尾注是两种常用的标注方法。它们不仅可以为读者提供额外的背景信息&#xff0c;还能帮助整理文章中的引用来源。下面我们就来详细的了解一下什么是脚注和尾注。 脚注 脚注&#xff08;Footnote&#xff09;…

回溯法与迭代法详解:如何从手机数字键盘生成字母组合

在这篇文章中&#xff0c;我们将详细介绍如何基于手机数字键盘的映射&#xff0c;给定一个仅包含数字 2-9 的字符串&#xff0c;输出它能够表示的所有字母组合。这是一个经典的回溯算法问题&#xff0c;适合初学者理解和掌握。 问题描述 给定一个数字字符串&#xff0c;比如 …

2024 第一次周赛

A: 题目大意 骑士每连续 i 天每天会得到 i 个金币&#xff0c;&#xff08;i 1&#xff0c; 2&#xff0c; 3 &#xff0c; …&#xff09;,那么展开看每一天可以得到的金币数&#xff1a;1 2 2 3 3 3 4 4 4 5 5 5 5 5 … 可以发现就是1个1 &#xff0c;2个2, 3个3…,那么我…

关于md5强比较和弱比较绕过的实验

在ctf比赛题中我们的md5强弱比较的绕过题型很多&#xff0c;大部分都是结合了PHP来进行一个考核。这一篇文章我将讲解一下最基础的绕过知识。 MD5弱比较 比较的步骤 在进行弱比较时&#xff0c;PHP会按照以下步骤执行&#xff1a; 确定数据类型&#xff1a;检查参与比较的两…

Django的请求与响应

Django的请求与响应 1、常见的请求2、常见的响应3、案例 1、常见的请求 函数的参数request是一个对象&#xff0c;封装了用户发送过来的所有请求相关数据。 get请求一般用来请求获取数据&#xff0c;get请求也可以传参到后台&#xff0c;但是传递的参数显示在地址栏。 post请求…

vue3 高德地图标注(飞线,呼吸点)效果

装下这两个 npm 忘了具体命令了&#xff0c;百度一下就行 “loca”: “^1.0.1”, “amap/amap-jsapi-loader”: “^1.0.1”, <template><div id"map" style"width: 100%;height: 100%;"></div> </template><script setup> …

论文笔记:RelationPrompt :Zero-Shot Relation Triplet Extraction

论文来源: ACL Findings 2022 论文链接:https://arxiv.org/pdf/2203.09101.pdf 论文代码:http://github.com/declare-lab/RelationPrompt 本篇论文是由阿里达摩院自然语言智能实验室于2022年发表的关于零样本关系抽取的顶会论文,本篇博客将记录我在阅读过程中的一些笔记…

​ceph掉电后无法启动osd,pgs unknown

处理办法&#xff1a; 进一步osd.0的日志检查发现提示unable to read osd superblock&#xff1a; 尝试fsck操作&#xff1a; ceph-objectstore-tool --data-path /var/lib/ceph/osd/ceph-0/ --type bluestore --op fsck 如果成功&#xff0c;则到此为止。 如果失败&#xf…

K8s简介及环境搭建

一、Kubernetes简介 kubernetes 的本质是一组服务器集群&#xff0c;它可以在集群的每个节点上运行特定的程序&#xff0c;来对节点中的容器进行管理。目的是实现资源管理的自动化&#xff0c;主要提供了如下的主要功能&#xff1a; 自我修复&#xff1a;一旦某一个容器崩溃&a…

游戏加速器最新口令兑换码,最低50小时免费领取

不是月卡买不起&#xff0c;而是薅羊毛更有性价比&#xff01;游戏党福音&#xff0c;今天为玩家们分享最新一批雷雷口令兑换码&#xff0c;为您的游戏之旅全面保驾护航&#xff01; 兑换码&#xff1a;8521 兑换码&#xff1a;9989 兑换码&#xff1a;211314 兑换码&#…

springmvc的处理流程

用户把请求发到前端控制器&#xff0c;前端控制器通过handlerMapping找到controller&#xff0c;controller调用service&#xff0c;service调用dao&#xff0c;从数据库拿到要获取的数据&#xff0c;然后modelandview给前端控制器&#xff0c;前端控制器通过viewresolver解析视…

仿IOS桌面悬浮球(支持拖拽、自动吸附、自动改变透明度与点击、兼容PC端与移动端)

使用 pointerdown/pointermove/pointerup 实现仿IOS桌面悬浮球效果&#xff0c;支持拖拽、指定拖拽选对容器&#xff0c;指定拖拽安全区、自动吸附、自动改变透明度与点击&#xff0c;兼容PC端与移动端。 效果展示 https://code.juejin.cn/pen/7423757568268304421 代码实现 …

计算机网络:数据链路层 —— PPP 点对点协议

文章目录 PPP 帧PPP帧的格式PPP帧的透明传输面向字节的异步链路面向比特的同步链路 PPP帧的差错检测 PPP 的工作状态 点对点协议&#xff08;Point-to-Point Protocol&#xff0c;PPP&#xff09;是目前使用最广泛的点对点数据链路层协议&#xff0c;用于在两个节点之间进行数据…

双目视觉搭配YOLO实现3D测量

一、简介 双目&#xff08;Stereo Vision&#xff09;技术是一种利用两个相机来模拟人眼视觉的技术。通过对两个相机获取到的图像进行分析和匹配&#xff0c;可以计算出物体的深度信息。双目技术可以实现物体的三维重建、距离测量、运动分析等应用。 双目技术的原理是通过两…

【最新华为OD机试E卷-支持在线评测】英文输入法(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)

🍭 大家好这里是春秋招笔试突围 ,一枚热爱算法的程序员 💻 ACM金牌🏅️团队 | 大厂实习经历 | 多年算法竞赛经历 ✨ 本系列打算持续跟新华为OD-E/D卷的多语言AC题解 🧩 大部分包含 Python / C / Javascript / Java / Cpp 多语言代码 👏 感谢大家的订阅➕ 和 喜欢�…

大数据-158 Apache Kylin 安装配置详解 集群模式启动

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; 目前已经更新到了&#xff1a; Hadoop&#xff08;已更完&#xff09;HDFS&#xff08;已更完&#xff09;MapReduce&#xff08;已更完&am…