将值从2个不同的活动传递给非startActivity的活动

时间:2018-11-20 19:39:06

标签: android android-activity

我要传递值的活动是应用程序的主要活动菜单。从这个活动中,我开始使用按钮启动所有活动。我想在标题中提到的同时从两个不同的活动中检索值,当我启动每个活动时,我想发送值。有帮助吗?

1 个答案:

答案 0 :(得分:1)

使用静态字段或方法

在要从中获取值的所有类中都有静态字符串字段(或用于计算然后返回字符串的方法),然后在活动菜单中获取它们并将其传递到您的startActivity意向中。 / p>

示例:

class activity-menu extends Activity{

    public void StartActivityC(){
        // Get value from Activity_A
        string value_A = Activity_A.myString;
        // Get value from Activity_B
        string value_B = Activity_B.myString;
        // Store both values in an Intent:
        Intent intent = new Intent(this, Activity_C.class);
         // store the string from Activity A under "value_A"
        intent.putExtra("value_A", value_A);
         // store the string from Activity B under "value_B"
        intent.putExtra("value_B", value_B);
        startActivity(intent);
    }

}

public class Activity_A extends Activity{
    public static String myString;
    public Activity_A(){
        myString = "this is from activity A";
    }
}

public class Activity_B extends Activity{
    public static String myString;
    public Activity_B(){
        myString = "this is from activity B";
    }
}

public class Activity_C extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get the Intent that started this activity and extract the strings:
        Intent intent = getIntent();

        String value_A = intent.getStringExtra("value_A");
        string value_B = intent.getStringExtra("value_B");

        // DONE!
    }   
}