군침이 싹 도는 코딩
액티비티 ( Activity ) 간의 단방향 데이터 전달법 ( putExtra, getIntent ) 본문
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("LifeCycleApp","onCreate 함수 실행");
button = findViewById(R.id.button);
editName = findViewById(R.id.editName);
editAge = findViewById(R.id.editAge);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = editName.getText().toString().trim();
String strAge = editAge.getText().toString().trim();
int age =Integer.parseInt(strAge);
// 두번째 액티비티를 실행시키는 코드 작성
// 인텐트를 만든다
// 인텐트란 어떤 액태비티가 어떤 액티비티를 실행 시키겠다는 것
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
// 새로운 액티비티에 전달할 데이터를 셋팅한다
// key, value 로 데이터 셋팅
intent.putExtra("name", name);
intent.putExtra("age", age);
startActivity(intent);
}
});
}
# Main Activity 코드
액티비티간의 데이터 전달에는 putExtra, getIntent를 사용한다
먼저 메인액티비티에 인텐트 객체 생성을하고 intent.putExtra를 사용해 다른 액티비티에
보낼 데이터를 셋팅한다 key, value로 데이터가 세팅된다
따라서 파라미터에 key, value로 세팅해주면 된다
그 뒤 startActivity에 인텐트변수를 넣어준다
public class SecondActivity extends AppCompatActivity {
TextView txtName;
TextView txtAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.i("LifeCycleApp","두번째 액티비티의 onCreate 함수 실행");
txtName = findViewById(R.id.txtName);
txtAge = findViewById(R.id.txtAge);
// 이 액티비티를 실행한 액티비티로부터 데이터를 받아오는 코드
// 인텐트를 가져오고 그 인텐트에 들어있는 키값으로 데이터를 받아온다
String name = getIntent().getStringExtra("name");
int age = getIntent().getIntExtra("age", 0);
// Intent intent = getIntent();
// String name = intent.getStringExtra("name");
txtName.setText(name);
txtAge.setText(age+""+"살");
}
# Second Activity 코드
받는쪽인 세컨트 액티비티에 getIntent().get데이터타입Extra(키값)을 사용해 데이터를 받는다
그 뒤 변수로 저장하고 받아온값을 출력해주면 된다
해당 코드에서는 나이와 이름을 입력받아 세컨트 액티비티에서 출력하도록 하였다
# 메인 액티비티 실행화면
# 세컨트 액티비티 실행화면
'Android' 카테고리의 다른 글
SharedPreference 저장하기 불러오기 ( putString, getString ) (0) | 2023.01.31 |
---|---|
액티비티 ( Activity ) 간의 양방향 데이터 전달법과 액티비티 백버튼 누를때 ( ActivityResultLauncher<Intent>, setResult ) (0) | 2023.01.30 |
액티비티( Activity )간의 화면 전환 방법 ( Intent ) (1) | 2023.01.30 |
액티비티 라이프 사이클 ( Activity Life cycle ) 의 주요 4개 함수 ( onCreate, onResume, onPause, onDestroy ) (0) | 2023.01.30 |
카운트 다운 타이머 ( CountDownTimer ) 사용법 (0) | 2023.01.27 |