프로그래밍/안드로이드[Android]
안드로이드 화면 전환시 데이터전달하기 [액티비티간 데이터 전달]
yohoi
2019. 5. 28. 17:04
이번글에서는 액티비티간 화면 전환시 간단하게 데이터 전달하는 방법에 대해 알려드리겠습니다.
목표로는 클릭을 했을때 이전 액티비티에서 정보를 전달하여 다음 액티비에서 받아 화면에 표시합니다.
Intent를 이용하여 데이터를 보내기 |
버튼 클릭시 데이터를 전달 하므로 코드는 다음과 같습니다.
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Intent intent = new Intent(getApplicationContext(),Main2Activity.class);
intent.putExtra("name","홍길동"); //String형태
intent.putExtra("age",25); //int형태
intent.putExtra("boolean",true); //boolean 형태
startActivity(intent);
}
});
화면 전환시 Main2Activity가 다음 이동할 액티비티입니다.
위의 소스와 같이 원하는 자료형에 맞게 작성하시면 됩니다.
Intent를 이용하여 데이터를 받기 |
화면전환이 되는 액티비티에서는 다음과 같이 데이터를 받으시면 됩니다.
Intent intent = getIntent();
String name = intent.getExtras().getString("name");
int age = intent.getExtras().getInt("age");
boolean bool = intent.getExtras().getBoolean("boolean");
그리고 간단하게 화면에 표시하도록 하겠습니다.
TextView nameText = findViewById(R.id.name);
TextView ageText = findViewById(R.id.age);
TextView boolText = findViewById(R.id.bool);
nameText.setText(name);
ageText.setText(String.valueOf(age));
boolText.setText(String.valueOf(bool));
자 그리고 확인을 해보시면
다음과 같이 클릭 하고 화면전환이 완료된 액티비티에서 데이터가 옮바르게 전달 된 것을 볼 수 있습니다.
이상입니다. 감사합니다.