在 Android 中的 Activity 之间传递数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2965109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:05:01  来源:igfitidea点击:

Passing data between activities in Android

android

提问by yokks

How do you pass data between activities in an Android application?

您如何在 Android 应用程序中的活动之间传递数据?

回答by Pentium10

in your current activity, create an intent

在您当前的活动中,创建一个意图

Intent i = new Intent(getApplicationContext(), ActivityB.class);
i.putExtra(key, value);
startActivity(i);

then in the other activity, retrieve those values.

然后在另一个活动中,检索这些值。

Bundle extras = getIntent().getExtras(); 
if(extras !=null) {
    String value = extras.getString(key);
}

回答by Patricia Heimfarth

Use a global class:

使用全局类:

public class GlobalClass extends Application
{
    private float vitamin_a;


    public float getVitaminA() {
        return vitamin_a;
    }

    public void setVitaminA(float vitamin_a) {
        this.vitamin_a = vitamin_a;
    }
}

You can call the setters and the getters of this class from all other classes. Do do that, you need to make a GlobalClass-Object in every Actitity:

您可以从所有其他类调用该类的 setter 和 getter。这样做,您需要在每个活动中创建一个 GlobalClass-Object:

GlobalClass gc = (GlobalClass) getApplication();

Then you can call for example:

然后你可以调用例如:

gc.getVitaminA()

回答by AlphaStack

Put this in your secondary activity

把它放在你的次要活动中

SharedPreferences preferences =getApplicationContext().getSharedPreferences("name", MainActivity.MODE_PRIVATE);

android.content.SharedPreferences.Editor editor = preferences.edit();

editor.putString("name", "Wally");
            editor.commit();

Put this in your MainActivity

把它放在你的 MainActivity 中

SharedPreferences preferences = getApplicationContext().getSharedPreferences("name", MainActivity.MODE_PRIVATE);

if(preferences.contains("name")){

Toast.makeText(getApplicationContext(), preferences.getString("name", "null"), Toast.LENGTH_LONG).show();

}