액티비티간 양방향 데이터 전달 방법
- ActivityResultLauncher 메소드를 사용
ActivityResultLauncher
다른 액티비티로 이동하고 이동된 액티비티가 종료 될 때 데이터 전달받는 소스 코드
onActivityResult 메소드 오버라이드
- startActivityResult.launch(Intent)에서 전달 받은 값(키로 호출)과 리퀘스트 코드 접근 하는 메소드
- 확인 : startActivityResult는 ActivityResultLauncher의 객체를 임의로 지정한 이름
- 주의 : onCreate() 메소드가 아닌 다른 영역에서 오버라이드 해야 함
- 데이터 전달(반환값)이 성공적이면 리퀘스트 코드는 0
- 전달 받은 값은 리퀘스트 코드 0으로 구분하여 코드 작성 (조건문 이용)
// MainActivity Override Method Define
ActivityResultLauncher<Intent> startActivityResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == 0) {
String returnData = result.getData().getStringExtra("returnData");
TextView returnText = findViewById(R.id.textReturn);
returnText.setText(returnData);
}
}
});
// MainAcivity
Intent intent = new Intent(MainActivity.this, SubActivity.class);
startActivityResult.launch(intent);
다른 액티비티에서 데이터 전달하는 방법은 동일하다.
이동된 액티비티에서 액티비티가 종료 될 때 값을 전달하는 소스 코드
- 값 전달은 단방향 데이터 전달과 같음
- 다만, setResult로 리퀘스트코드와 인텐트 객체 정보 전달
// SubActivity
Intent intent = new Intent(SubActivity.this, MainActivity.class);
intent.putExtra("dataKey", dataValue);
setResult(0, intent);
'Android' 카테고리의 다른 글
| SharedPreferences 를 이용한, 데이터 저장과 불러오기 (0) | 2023.01.31 |
|---|---|
| 액티비티 백버튼 누를 때 / onBackPressed() (0) | 2023.01.30 |
| 액티비티간 단방향 데이터 전달 방법 (0) | 2023.01.30 |
| 액티비티간의 화면 전환 방법 / Intent 와 startActivity 함수 (0) | 2023.01.30 |
| 활동 수명 주기 (Activity Life Cycle) (0) | 2023.01.30 |