Passing a variable from one activity to two new activities in Android Studio

时间:2018-03-08 22:16:00

标签: java android android-studio

I was wondering if it's possible to pass the same variable from one activity in Android studio to two separate activities, I've had a search and cannot see if it's possible or not using intents.

The "shareInt" below is a int which is updated as the application progresses, upon ending the application it is passed to the 2nd class, however I would also like it passed to the 3rd class at the same time as the user is provided with two options. Is it possible?

Intent intent = new Intent(1st.this, 2nd.class); 
Bundle b = new Bundle();
b.putInt("data", shareInt);
intent.putExtras(b);
startActivity(intent);

Thanks in advance.

2 个答案:

答案 0 :(得分:0)

为什么不做一些像

这样的事情
 if (select a)
     {
         Intent intent = new Intent(1st.this, a.class); 
         Bundle b = new Bundle();
         b.putInt("data", shareInt);
         intent.putExtras(b);
         startActivity(intent);
     }
else if (select b)
     {
          Intent intent = new Intent(1st.this, b.class); 
          Bundle b = new Bundle();
          b.putInt("data", shareInt);
          intent.putExtras(b);
          startActivity(intent);
     }

或者如果您想同时将它发送给他们两个,请使用EventBus等库。

答案 1 :(得分:0)

我不确定你的意思,如果我理解正确,请告诉我。用户有选项A,它启动活动A,选项B启动活动B,你想将int传递给用户选择的任何活动吗?

如果这是你想要做的事,那就简单了。我假设用户会看到ButtonAButtonB

//if the user selects A 
public void btnAPress(View v)
{
  Intent intent = new Intent(1st.this, activityA.class); 
  intent.putExtras("share", shareInt);
  startActivity(intent);
}

//if the user selects B 
public void btnBPress(View v)
{
  Intent intent = new Intent(1st.this, activityB.class); 
  intent.putExtras("share", shareInt);
  startActivity(intent);

}

请务必询问您是否有任何跟进问题