Android2012. 1. 9. 13:43
[목표]
Activity 에 ImageView를 추가하고, ImageView를 클릭했을 때, onTouch 이벤트를 받는다.
이벤트는  ACTION_DOWN, ACTION_UP, ACTION_MOVE를 받아야 한다.

ImageButton이 아닌, ImageView 를 하나 만든다.

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <imageview
        android:id="@+id/iv_facebook"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/img_facebook"
        android:contentdescription="@string/todo" >
    </imageview>

</linearlayout>


화면에 보여줄 이미지뷰에 onTouch 리스너를 등록하고 각각의 메시지를 받으면 로그를 찍어본다.
public class OnTouchDemoActivity extends Activity implements OnTouchListener {
    @Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ImageView ivFacebook = (ImageView) findViewById(R.id.iv_facebook);
		ivFacebook.setOnTouchListener(this);
	}
    
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		int action = event.getAction();
		int id = v.getId();
		
		if(action==MotionEvent.ACTION_DOWN) {
			if(id == R.id.iv_facebook) {
				Log.d("TAG", "OnTouch : ACTION_DOWN");
			}
        }
        else if(action==MotionEvent.ACTION_UP){
        	if(id == R.id.iv_facebook) {
        		Log.d("TAG", "OnTouch : ACTION_UP");
    		}
        }
        else if(action==MotionEvent.ACTION_MOVE){
        	if(id == R.id.iv_facebook) {
        		Log.d("TAG", "OnTouch : ACTION_MOVE");
    		}
        }
		return false;
	}
}



[문제점]
이미지 버튼을 아무리 클릭해도, 위와 같이 ACTION_DOWN 메시지만 불려지고, UP, MOVE 메시지는 발생하지 않는다.

[해결책]
ImageView의 속성 중 "clickable"속성을 켠다(On).

ImageView ivFacebook = (ImageView) findViewById(R.id.iv_facebook);
ivFacebook.setOnTouchListener(this);
ivFacebook.setClickable(true);  // If you set this, you can get all the touch-actions
 또는,
<imageview
    android:id="@+id/iv_facebook"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/img_facebook"
    android:clickable="true"
    android:contentdescription="@string/todo" >
</imageview>


이후에는 DOWN, MOVE, UP 순서로 메시지들이 전달되는 것을 알 수 있다.



[전체소스]
    다운로드 


Posted by 데브로망스