본문 바로가기
앱 만들기/안드로이드 study

안드로이드의 기술 # 버튼 이벤트 처리.

by 나도처음이야 2020. 9. 11.
반응형

두개의 버튼이 있고, 그 이벤트를 하나의 함수에서 실행하고 싶다면?

물론, 여러 방법이 있겠지만 오늘은 XML onClick 에 함수를 등록하고

그 함수 내에서 분기하는 방법을 다루어 봅니다.

1. 버튼 이벤트 메서드를 만든다.

1
2
3
4
5
6
7
8
9
10
//버튼을 구별하는 방법.
    public void onButtonClicked(View view){
 
        if(view.getId() == R.id.flagButton){
            Log.d("test""flagButton");
        }else{
            Log.d("test""GameButton");
        }
 
    }
cs

위와 같이 버튼 클릭시 반응을 메소드를 만듭니다.

중요한 것은 인자값으로 View view 를 넣어주어야 한다는 것!

바로 이 View 가 각각의 버튼을 구별합니다.  

하기 코드를 통해서 말이죠. 

 

if(view.getId() == R.id.flagButton)

 

물론, view 객체를 구별하는 여러방법이 있지만, 여기서는 getId()를 사용해 보았습니다.

필자는 하기처럼, 두개의 버튼을 구별 해 봅니다.

 

2. 마지막으로 클릭 메소드를 XML에 하기 처럼 등록 해 줍니다.

각각 두개의 버튼에 등록합니다.

 android:onClick="onButtonClicked"

 

첫번째 버튼

1
2
3
4
5
6
7
8
9
10
11
12
13
 <Button
        android:id="@+id/gameButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
 
        android:onClick="onButtonClicked"
 
        android:text="Game of the flag"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/flagButton"
        app:layout_constraintVertical_bias="0.03" />
cs

두번째 버튼

1
2
3
4
5
6
7
8
9
10
11
12
13
 <Button
        android:id="@+id/gameButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
 
        android:onClick="onButtonClicked"
 
        android:text="Game of the flag"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/flagButton"
        app:layout_constraintVertical_bias="0.03" />
cs

 

위와 같이 처리하면, 

버튼 이벤트 리스너 객체를 별도로 만들지 않아도 되는 장점이 있습니다.

상황에 따라 이벤트 처리 기술은 달라지겠지만, getid() 를 사용하는 방법도 체크해보면 좋겠습니다.

감사합니다.

반응형

댓글