Java, Android
[Android] 클릭한 좌표의 View 얻기
수동애비
2024. 4. 25. 12:11
반응형
각 뷰 컨트롤 마다 개별적으로 Listener 를 설정하지 않고 화면에서 특정 위치를 터치 시
해당 위치에 존재하는 View 를 얻어야 할 경우 아래 코드를 이용하여 얻을 수 있다.
private Rect mViewRect = new Rect();
public View getViewOfPointer(ViewGroup rootView, final int x, final int y) {
for (int i = 0; i < rootView.getChildCount(); i++) {
View child = rootView.getChildAt(i);
if (child instanceof ViewGroup){
View findView = getViewOfPointer((ViewGroup) child, x, y);
if (findView != null) {
return findView;
}
}
else {
if (child.getGlobalVisibleRect(mViewRect)) {
if (mViewRect.contains(x, y)) {
return child;
}
}
}
}
return null;
}
엑티비티의 dispatchTouchEvent(MotionEvent ev) 를 오버라이드 하여 터치 좌표를 획득하여 getViewPointer 를 통해 View 를 획득한다.
아래 코드는 터치한 위치의 View 가 EditText 가 아닐 경우 자판을 숨기도록 하는 코드이다.
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
int x = (int)ev.getX(), y = (int)ev.getY();
View findView = getViewOfPointer((ViewGroup)getWindow().getDecorView(),x, y);
if (findView != null) {
if (findView instanceof EditText) {
return super.dispatchTouchEvent(ev);
}
}
View focusView = getCurrentFocus();
if (focusView != null) {
focusView.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
getWindow().getDecorView().requestLayout();
}
}
}
return super.dispatchTouchEvent(ev);
}
터치나 드래그 시 너무 많은 이벤트가 들어오므로 MotionEvent.ACTION_UP 일 경우에만 좌표를 추출하여 View 를 획득.
획득한 View 에서 인스턴스 타입이나 필요한 정보를 얻어 처리를 하면 된다.