Android

Android Intent 전환 (액티비티 전환)

션 쿠 2019. 7. 15. 01:32

액티비티 A와 액티비티 B가 있다.

 

코드상으로 현재 액티비티 A의 어떤 Component의 onClick()함수를 통해 액티비티 B로 전환하려고 한다.

 

이럴 때엔 어떻게 코드를 써야할까?

 

 

1. 액티비티 전환

Intent intent = new Intent(Activity_A.this, Activity_B.class);
startActivity(intent);

이렇게만 쓰면 onClick()에서 바로 액티비티를 B로 전환할 수 있다.

 

하지만, Activity A위에 있지만 다른 클래스에서 startActivity를 Call 할 수가 없는 상황에서는, 무슨 방법으로든 현재 context를 받아와서 다음과 같이 써주면 된다.

mContext = ???		//call

Intent intent = new Intent(mContext, Activity_B.class);
mContext.startActivity(intent);

context는 보통 constructor를 통해 받아오거나, ViewGroup Parameter을 통해 가져온다.

 

 

2. 액티비티 간 데이터 전달

 

액티비티 간에 String이나 Integer 등의 객체를 주고 받고 싶을 때가 있을 것이다.

 

그럴 때에는 intent의 putExtra()를 이용하면 가능하다.

전환하기 직전에 Key-Value와 같이 데이터들을 짝지어 넣어주면 된다.

Intent intent = new Intent(Activity_A.this, Activity_B.class);
intent.putExtra("PlayerID", infos.get(pos).getSummoner().getAccountId());
startActivity(intent);

그러면 액티비티 B에서 다음과 같이 받는다.

Intent intent = getIntent();
String playerAccountID = intent.getStringExtra("PlayerID");

위와 같이 키와 데이터가 짝으로 되어있어 HashMap처럼 쉽게 값을 전달받을 수 있다.

 

받을 때 사용하는 함수는 전달할 때 넣은 파라미터의 자료형에 맞춰줘야 한다.