5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

タッチイベント ACTION_UP を別のビューで拾う

Posted at

概要

あるビューAを押下して指をスライドさせ、別のビューB上で指を離したときにビューBの OnTouchEvent を呼ぶ方法。

参考

記事の内容は 100% 下記ページに拠っています。
http://stackoverflow.com/questions/12980156/detect-touch-event-on-a-view-when-dragged-over-from-other-view

方法

タッチイベント ACTION_UP は ACTION_DOWN が発生したビューにしか通知されない仕様らしい。
そのため、別のビューに ACTION_UP を送りたいときはタッチイベント発生元から別のビューに人為的に通知してあげる必要がある。

下記はボタンとテキストビューがあるアクティビティサンプル。
ボタンをタッチして指をスライドし、テキストビュー上で指を離すとテキスト内容が変わる。


public class MyActivity extends Activity {

	static final String TAG ="MyActivity";

    /**
     * @brief    入力 x, y がビューの領域内かどうかを判定する.
     * @return   true: 領域内, false: 領域外.
     */
	private boolean inViewBounds(final View view, int x, int y){
		Rect outRect = new Rect();
		view.getDrawingRect(outRect);
		int[] location = new int[2];
		view.getLocationOnScreen(location);
		outRect.offset(location[0], location[1]);
		return outRect.contains(x, y);
	}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

	    final TextView text = (TextView)findViewById(R.id.textView);
	    final Button button = (Button)findViewById(R.id.button);

	    text.setOnTouchListener(new View.OnTouchListener() {
		    @Override
		    public boolean onTouch(View v, MotionEvent event) {
			    switch (event.getAction()) {
				    case MotionEvent.ACTION_UP:
					    TextView vv = (TextView)v;
					    vv.setText(event.getX() + ", " + event.getY());
					    break;

				    default:
					    Log.v(TAG, "another event on view");
			    }

			    return false;
		    }
	    });

	    button.setOnClickListener(new View.OnClickListener() {
		    @Override
		    public void onClick(View v) {
			    // do nothing
		    }
	    });

	    button.setOnTouchListener(new View.OnTouchListener() {
		    @Override
		    public boolean onTouch(View v, MotionEvent event) {
			    int x = (int)event.getRawX();
			    int y = (int)event.getRawY();

			    if(event.getAction() == MotionEvent.ACTION_UP){
				    if(inViewBounds(text, x, y))
				    {
					    Log.v(TAG, "on release text");
					    text.dispatchTouchEvent(event);
				    }
				    else if(inViewBounds(button, x, y)){
					    Log.d(TAG, "on release button");
				    }
			    }
			    return false;
		    }
	    });
    }
}

個人的に調べた範囲ではこの方法が一番よさそうだった。
(他の方法はうまくいかなかった)

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?