0

过去两天我试图在 Android API7 中编写简单的拖放功能,但我一直遇到问题。现在有了触摸监听器。我使用 onTouchListener 但 onTouch 方法只有当我在 UI 元素上按下屏幕时才会调用它。当我在另一个地方按下屏幕然后我将手指移到指定 onTouchListener 的元素上方时,什么也没发生。为什么?是否有任何适用于 android 的侦听器,它可以在不点击 UI 元素所在位置的屏幕的情况下捕获触摸事件?感谢您的帮助,因为我今天要疯了;)

4

1 回答 1

0

onTouchListener 仅用于视图。你可以将它用于任何布局(例如,LinearLayout)。如果您的布局带有“fill_parent”参数,它将适用于您的所有屏幕。您还需要控制您的 ACTION_DOWN、UP 和 MOVE 参数。也许这个样本可以帮助你:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;

public class main extends Activity implements OnTouchListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout ll =(LinearLayout)this.findViewById(R.id.ll);
    ll.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event)
{
    int action=event.getAction();
    StringBuilder str=new StringBuilder();
    str.append("\nActrion type: ");

    switch(action)
    {
        case MotionEvent.ACTION_DOWN: str.append(«ACTION_DOWN\n»);break;
        case MotionEvent.ACTION_MOVE: str.append(«ACTION_MOVE\n»);break;
        case MotionEvent.ACTION_UP: str.append(«ACTION_UP\n»);break;
    }

    Log.v(«Mytag», str.toString());
    return true;
}
}
于 2012-08-11T20:56:10.757 回答