使用Intent傳值及回傳值
阿新 • • 發佈:2018-05-12
CA request int tar edi 字符串 AS button tst
簡單傳值
FirstActivity.java
findViewById(R.id.button).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.putExtra("extra_data","data"); // 傳字符串, 更多傳值方法 startActivity(intent); } });
SecondActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // 獲取Intent對象 Intent intent = getIntent(); // 根據key獲取value String extra_data = intent.getStringExtra("extra_data"); // 獲取一個沒有的可以 結果 null String extra_data2 = intent.getStringExtra("extra_data2"); Log.i(TAG, "onCreate: " + extra_data + extra_data2); }
回傳值:
修改FirstActivity.java
/** * 監聽獲取activity返回的數據 * @param requestCode 傳入的請求碼 * @param resultCode 處理結果碼 * @param data intent數據 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 1: if (resultCode == RESULT_OK) { String resultData = data.getStringExtra("data_return"); Log.i(TAG, "onActivityResult: " + resultData); } break; default: } }
修改SecondActivity.java
button = (Button) findViewById(R.id.button2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.putExtra("data_return", "hello FirstActivity"); // 給上一個活動返回數據 setResult(RESULT_OK, intent);// 回調(FirstActivity.java中)onActivityResult方法 finish(); } });
使用Intent傳值及回傳值