【问题标题】:Passing 3 elements (Intents)传递 3 个元素(意图)
【发布时间】:2013-04-12 21:30:16
【问题描述】:

我想将以下三个元素从一个活动传递到另一个活动:

String a = "a";
String b = "b";
String c = "c";

我尝试了以下方法但没有成功:

在主活动(MainActivity)中:

Bundle extras = new Bundle();
extras.putString("a", a);
extras.putString("b", b);
extras.putString("c", c);
Intent intent = new Intent(MainActivity.this, SubActivity.class);
intent.putExtras(extras);
startActivity(intent);

在子活动(SubActivity)中:

Bundle extras = new Bundle();
String a = extras.getString("a");
String b = extras.getString("b");
String c = extras.getString("c");

【问题讨论】:

    标签: java android string android-intent bundle


    【解决方案1】:

    在你的子活动中

    代替

     Bundle extras = new Bundle();  
    

    使用下面的

     Bundle extras = getIntent().getExtras();
     if(extras!=null)
     {
           String a = extras.getString("a");
           String b = extras.getString("b");
           String c = extras.getString("c");
     } 
    

    【讨论】:

      【解决方案2】:

      在 SubActivity 中,您应该通过调用 getIntent().getExtras(); 来获取 Bundle,而不是通过创建新的 Bundle。

      public class SubActivity extends Activity {
          public void onCreate(Bundle saved) {
              super.onCreate(saved);
              setContentView(...);
      
              Bundle extras = getIntent().getExtras();
              if (extras != null) {
                  // call extras.getString() here
              }
          }
      }
      

      【讨论】:

        【解决方案3】:
        String array[] = {"a","b","c"};
        
        Intent i = new Intent(A.this, B.class);
        i.putExtra("array", array);
        startActivity(i);
        

        在活动 B 中:

        Bundle extras = getIntent().getExtras();
        String[] arrayB = extras.getStringArray("array");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-27
          • 1970-01-01
          • 2014-03-07
          • 1970-01-01
          • 2015-07-15
          相关资源
          最近更新 更多