Activity传数据(通过Application全局方式,此方式不建议。)

新建 MyApplication

import android.app.Application;

/**
 * @author iLife.Fy
 * @create 2022/2/2 17:23
 */
public class MyApplication extends Application {
    private String data;

    @Override
    public void onCreate() {
        super.onCreate();
        data = null;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

在AndroidManifest文件中添加第六行代码(android:name=".MyApplication")以初始化MyApplication

<?xml version="1.0" encoding="utf-8"?>

<application
    android:name=".MyApplication"
    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.TmpProjects">
    <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>
</application>

在主界面传信息

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

/**
 * @author 71240
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btnNextAct).setOnClickListener(this::nextAct);
    }

    private void nextAct(View view) {
        String data = getClass().getSimpleName() + ":你好,我是主界面";
        // 数据保存至 MyApplication
        MyApplication application = (MyApplication) getApplication();
        application.setData(data);
        // 转至其他Activity
        startActivity(new Intent(this, OtherActivity.class));
        finish();
    }
}

在其他界面接受信息

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

import androidx.appcompat.app.AppCompatActivity;

/**
 * @author 71240
 */
public class OtherActivity extends AppCompatActivity {
    private String data = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        findViewById(R.id.btnGetData).setOnClickListener(this::getData);
    }

    private void getData(View view) {
        if (data == null) {
            MyApplication application = (MyApplication) getApplication();
            data = application.getData() + "\n" + getClass().getSimpleName()
                    + ":主界面你好,我是其他界面,已经收到你发的信息";
        }
        Toast.makeText(this, data, Toast.LENGTH_LONG).show();
    }
}

参考:http://blog.sina.com.cn/s/blog_c2a099fc0102v5o0.html

上一篇:IOS开发之UIScrollView约束布局


下一篇:【备战金三银四】2022最新Android中高级大厂面试题汇总,高薪必备(文末巨量资料免费分享)