본문 바로가기

개발자/Android

안드로이드 위젯의 클릭 이벤트를 처리하는 4가지 방법 - 리스너 인터페이스 구현

반응형



안드로이드 위젯의 이벤트를 처리하는 4가지 방법 - 리스너 인터페이스 구현


클릭 이벤트에 대해서는 콜백 메서드가 정의되어 있지 않으며 반드시 리스너로 이벤트를 받아서 처리해야 한다. 맨아래에 레이아웃 파일이 있다. 


방법 1 : findViewById 메서드로 xml 레이아웃에 정의된 R.id.apple 버튼 객체를 찾고 임시 리스너 객체를 생성하여 버튼의  setOnClickListener 메서드로 등록을 한다. 어렵지만 꼭 알아두어야 할 문법~


package exam.andexam;


import android.app.*;

import android.os.*;

import android.view.*;

import android.widget.*;


// 임시 객체로 핸들러 만들기


public class C06_Fruit extends Activity {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.c06_fruit);


Button btnApple=(Button)findViewById(R.id.apple);

btnApple.setOnClickListener(new Button.OnClickListener() {

public void onClick(View v) {

TextView textFruit=(TextView)findViewById(R.id.fruit);

textFruit.setText("Apple");

}

});


Button btnOrange=(Button)findViewById(R.id.orange);

btnOrange.setOnClickListener(new Button.OnClickListener() {

public void onClick(View v) {

TextView textFruit=(TextView)findViewById(R.id.fruit);

textFruit.setText("Orange");

}

});

}

}



방법 2 : 액티비티가  implements View.OnClickListener 를 통하여 OnClickListener  인터페이스를 직접 구현하도록 하였다. 리스너가 액티비티 자신인 this 가 된다. 


콜백은 특정 뷰 클래스 소속이므로 이벤트 발생 대상이 정해져 있다. 그러니 리스너는 여러 위젯(심지어 다른 종류의 위젯끼리도)에 의해 공유될 수 있으므로 대상 뷰가 누구인지 전달 받아야 한다. 뷰를 전달해 주고 void onClick(View v)  뷰의 getId()  를 클릭 된 버튼을 알아내고 처리해 준다.


액티비티를 리스너로 사용한다는 것이 부담스러운 코드.


// 핸들러 통합하기 - 인터페이스 구현


public class C06_Fruit extends Activity implements View.OnClickListener {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.c06_fruit);


Button btnApple=(Button)findViewById(R.id.apple);

btnApple.setOnClickListener(this);

Button btnOrange=(Button)findViewById(R.id.orange);

btnOrange.setOnClickListener(this);

}


public void onClick(View v) {

TextView textFruit=(TextView)findViewById(R.id.fruit);

switch (v.getId()) {

case R.id.apple:

textFruit.setText("Apple");

break;

case R.id.orange:

textFruit.setText("Orange");

break;

}

}

}


방법 3 : mClickListener 멤버는 View.OnClickListener 인터페이스를 구현하는 익명 클래스 타입으로 선언하고, 마찬가지로  onClick(View v) 에서 처리해준다. 위젯의 리스너를 처리하는 가장 좋은 방법이자.


findViewById(R.id.apple).setOnClickListener(mClickListener);

findViewById(R.id.orange).setOnClickListener(mClickListener);


두 버튼의 클릭 리스너 등록 메서드로 mClickListener 멤버를 전달한다.


//위젯의 리스너를 처리하는 가장 좋은 방법

// 핸들러 통합하기 - 인터페이스 구현 멤버 객체

public class C06_Fruit extends Activity {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.c06_fruit);


findViewById(R.id.apple).setOnClickListener(mClickListener);

findViewById(R.id.orange).setOnClickListener(mClickListener);

}


Button.OnClickListener mClickListener = new View.OnClickListener() {

public void onClick(View v) {

TextView textFruit=(TextView)findViewById(R.id.fruit);

switch (v.getId()) {

case R.id.apple:

textFruit.setText("Apple");

break;

case R.id.orange:

textFruit.setText("Orange");

break;

}

}

};

}




마지막 방법


이벤트 리스너는 코드에서 작성하는 것이 원칙이지만 클릭 이벤트만은 예외적으로 XML 문서에서 onClick 속성으로 지정할 수 있다. xml 문서의 Button 엘리먼트 속성에 다음을 추가한다.


android.onClick="mOnClick" 


코드에는 반드시 이 메서드가 있어야 하며, 클릭 이벤트 핸들러와 원형이 일치해야 한다.

코드를 구현하면


public class C06_Fruit2 extends Activity {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.c06_fruit2);

}


public void mOnClick(View v) {

TextView textFruit=(TextView)findViewById(R.id.fruit);

switch (v.getId()) {

case R.id.apple:

textFruit.setText("Apple");

break;

case R.id.orange:

textFruit.setText("Orange");

break;

}

}

}



예제에 쓰인 Layout 파일 - xml 코드


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:gravity="center_horizontal" 

    >


    <TextView

        android:id="@+id/fruit"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textColor="#ffff00"

        android:textSize="40sp"

        android:text="과일"

        />

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="fill_parent"

        >

        <Button 

            android:id="@+id/apple"

            android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/applename"

        />

        <Button 

            android:id="@+id/orange"

            android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/orangename"

        />

</LinearLayout>

</LinearLayout>


-끝-



반응형

캐어랩 고객 지원

취업, 창업의 막막함, 외주 관리, 제품 부재!

당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약, 아이디어는 있지만 구현할 기술이 없는 막막함.

우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.

이제 고민을 멈추고, 캐어랩을 만나세요!

코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.

제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!

귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.

지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.

카카오 채널 추가하기

카톡 채팅방에서 무엇이든 물어보세요

당신의 성공을 위해 캐어랩과 함께 하세요.

캐어랩 온라인 채널 바로가기

캐어랩