단방향
인텐트를 만들어 화면 띄우는 코드를 세팅
그 밑에 다른 액티비티에 전달할 데이터를 세팅
// 다른 액티비티를 실행시키는 코드
// 인텐트를 만든다.
// 인텐트란, 어떤 액티비티가 어떤 액티비티를 띄우겠다 라는 의도
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
// 액티비티에 데이터를 전달하는 방법
intent.putExtra("name", name);
intent.putExtra("age", age);
startActivity(intent);
위처럼 전달하는 코드를 작성하면 데이터를 받아올 액티비티(SecondActivity)는 데이터 받는 코드를 작성
// 데이터가 넘어온게 있으면 데이터를 받아준다.
String name = getIntent().getStringExtra("name");
age = getIntent().getIntExtra("age", 0);
양방향
SecondActivity 에서 Back 을 눌렀을때 이벤트 처리하는 코드 작성
// 백버튼 눌렀을때 동작하는 코드 작성
getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Intent intent = new Intent();
intent.putExtra("age", age);
setResult(1000, intent);
finish();
}
});
ActivityResultLauncher를 사용하여 SecondActivity 로부터 결과를 받아온다.
ActivityResultLauncher<Intent> launcher =
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult o) {
Log.i("LIFE MAIN", "onActivityResult 실행");
// 내가 실행한 액티비티로부터 데이터를 받아오는 부분
if (o.getResultCode() == 1000){
Log.i("LIFE MAIN", "데이터를 받아온다.");
int age = o.getData().getIntExtra("age",0);
txtAge.setText("10년 후 나이는 "+age+"세");
}
}
});
지정한 액티비티 시작
launcher.launch(intent);
'Android Studio' 카테고리의 다른 글
[Android Studio] Json 데이터 파싱 (0) | 2024.06.11 |
---|---|
[Android Studio] 안드로이드 네트워크 통신 Volley 라이브러리 (1) | 2024.06.11 |
[Android Studio] Activity 라이프 사이클 Life Cycle (0) | 2024.06.07 |
[Android Studio] AlertDialog (0) | 2024.06.05 |
[Android Studio] Toast / Snackbar (0) | 2024.06.05 |