티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Start an Activity with a parameter

매개변수를 사용하여 액티비티 시작하기

 문제 내용 

I'm very new on Android development.

저는 안드로이드 개발에 매우 새로운 사람입니다.

 

I want to create and start an activity to show information about a game. I show that information I need a gameId.

게임 정보를 보여주는 액티비티를 만들고 시작하려고 합니다. 저는 그 정보를 보여주기 위해 게임 ID가 필요합니다.

 

How can I pass this game ID to the activity? The game ID is absolutely necessary so I don't want to create or start the activity if it doesn't have the ID.

이 게임 ID를 액티비티에 전달하는 방법은 무엇인가요? 게임 ID가 없으면 액티비티를 생성하거나 시작하지 않기 때문에 게임 ID가 절대적으로 필요합니다.

 

It's like the activity has got only one constructor with one parameter.

액티비티는 하나의 매개변수를 가진 단일 생성자만 가지고 있는 것과 같습니다.

 

How can I do that?

어떻게 해야 할까요?

 

Thanks.

감사해요.

 

 

 

 높은 점수를 받은 Solution 

Put an int which is your id into the new Intent.

Int로 이루어진 ID를 새로운 Intent에 넣는다.
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("key", 1); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent);
finish();

 

Then grab the id in your new Activity:

그런 다음 새로운 액티비티에서 ID를 가져옵니다.
Bundle b = getIntent().getExtras();
int value = -1; // or other values
if(b != null)
    value = b.getInt("key");

 

 

 가장 최근 달린 Solution 

Kotlin code:

코틀린 코드:

 

Start the SecondActivity:

두 번째 액티비티 시작:
startActivity(Intent(context, SecondActivity::class.java)
    .putExtra(SecondActivity.PARAM_GAME_ID, gameId))

 

Get the Id in SecondActivity:

두 번째 액티비티에서 ID 가져오기:
class CaptureActivity : AppCompatActivity() {

    companion object {
        const val PARAM_GAME_ID = "PARAM_GAME_ID"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gameId = intent.getStringExtra(PARAM_GAME_ID)
        // TODO use gameId
    }
}

 

where gameId is String? (can be null)

여기서 gameId는 String? (null이 될 수 있음)

 

 

 

출처 : https://stackoverflow.com/questions/3913592/start-an-activity-with-a-parameter

반응형
댓글
공지사항
최근에 올라온 글