2016-09-21 8 views
0

私のアプリにはボタンがあります。私が達成したいのは、ボタンの上に指をドラッグすると、メソッドが呼び出されるということです。Android - ボタンの行をスライドするときのontouchイベントのトリガー

私のコードは、これまでのようになります。

レイアウト:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:orientation="horizontal" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.a4web.example.MainActivity"> 

</LinearLayout> 

のJava:

public class MainActivity extends AppCompatActivity { 
LinearLayout rootView; 

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

    rootView = (LinearLayout) findViewById(R.id.activity_main); 

    for(int i=0; i<5; i++){ 
     Button button = new Button(this); 
     button.setText(i); 
     button.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 

       switch (event.getAction()){ 
        case MotionEvent.ACTION_DOWN: 
         doSomething(); 
         break; 
       } 

       return false; 
      } 
     }); 
     rootView.addView(button); 
    } 
} 

私はボタンを押したときにのみ呼び出される私の方法のdoSomething。どのように私はそれがボタンの上にドラッグするときに呼び出されることを達成することができます。どのようなイベントを聞くべきですか?

+0

あなたのSwipeListenerを得るためにOnTouchListenerを上書きすることができます。この例を使用するhttp://stackoverflow.com/a/12938787/3286614 – Rachit

答えて

0

これを行うには、ボタンを押して離したときにのみトリガーするonClickListenerを使用する必要はありません。

MotionEvent.ACTION_DOWN(押すとき)、MotionEvent.ACTION_MOVE(指をドラッグしたとき)、MotionEvent.ACTION_UP(ボタンを離したとき)の3つのイベントに対してonTouchListenerが機能する場合でも、ボタンを押しながらドラッグします。 これは、最初にボタンの外側をクリックすると、ボタンにドラッグイベントが表示されないことを意味します。

どこでもクリックしてボタン上でドラッグイベントを確認したい場合、これはやっかいな方法です。

私はあなたのすべてのビューをcliccableにして、ビュー全体にonTouchListenerを実装し、指があなたのビューの特定の部分にあるときにチクチクすることをお勧めします。

このようにするには、ボタンをクリックできないようにすることが重要です。そうしないと、ビュー全体がまっすぐにならないようになります。

あなたはこのリポジトリに見ることができcliccableビューを実装する方法を学びたいのであれば

https://github.com/alessandroargentieri/JoyStick

関連する問題