개발자/Android

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

지구빵집 2012. 11. 22. 10:00
반응형



안드로이드 위젯의 이벤트를 처리하는 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>


-끝-



반응형