Android學習筆記06—使用Intent傳遞參數的兩種方式

使用Intent在不同activity間進行傳參的兩種方法

  • 使用Intent的putExtra()方法進行參數傳遞

傳遞參數

  Intent intent = new Intent(FromActivity.this, ToActivity.class);
  /*設置inent的傳遞參數*/
  intent.putExtra("args", args);
  startActivity(intent);

接收參數

  // 接收傳入的intent對象
  Intent intent = getIntent();
  if(intent != null){
      //獲取intent中的參數
      String regAccount = intent.getStringExtra("args");
  }
  • 使用Bundle對象將參數封裝進行傳遞

封裝并傳遞參數

  Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
  // 使用Bundle對象進行傳參,做一層封裝
  Bundle bundle = new Bundle();
  bundle.putString("accountName",accountName);
  bundle.putInt("accountAge",accountAge);
  // intent對象綁定bundle對象
  intent.putExtras(bundle);
  startActivity(intent);

接收參數

  // 接受傳入的intent對象
  Intent intent = getIntent();
  if(intent != null){
    // 獲取Bundle對象中的參數
    Bundle bundle = intent.getExtras();
    if(bundle != null){
        String accountName = bundle.getString("accountName", "");
        Int accountAge = bundle.getInt("accountAge", 1);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容