简体   繁体   English

视图中的OnTouchListener-Android

[英]OnTouchListener in a View - Android

When I am adding a listener 'OnTouchListener' to a View, it doesn't register. 当我向视图添加侦听器“ OnTouchListener”时,它不会注册。 Here is my code: 这是我的代码:

GUI gui;
boolean guis = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    gui = new GUI(getBaseContext());
    gui.setOnTouchListener(this);
    setContentView(gui);
}

When I do setOnTouchListener(), I put 'this' as a parameter.. Should that be something else? 当我执行setOnTouchListener()时,我将“ this”作为参数。

I let the GUI class implement OnTouchListener and adds a OnTouch method... But I put 我让GUI类实现OnTouchListener并添加了OnTouch方法。

Log.w("AA","Hello")

In the OnTouch method, yet it doesn't log that at all. 在OnTouch方法中,它根本不会记录下来。

You can do the following 您可以执行以下操作

  public class MainActivity extends Activity implements OnTouchListener{
    GUI gui;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        gui = new GUI(MainActivity.this);
            setContentView(gui);
    gui.setOnTouchListener(this);
}


@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    Log.w("AA","Hello")
    return true;
}

Or you can override the onTouch in your gui view 或者,您可以在gui视图中覆盖onTouch

public class GUI extends View{

Context mcontext; 
public MyView(Context context) {
    super(context);
            mcontext=context; 
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Toast.makeText(mcontext, "View clicked", 1000).show();
switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        // do something
        break;
    case MotionEvent.ACTION_MOVE:
        // do something
        break;
    case MotionEvent.ACTION_UP:
       //do something
        break;
}
return true;
}

As Luksprog commented this refer's to the current context. 正如Luksprog所说的,这是指当前上下文。

If you do this gui.setOnTouchListener(this); 如果您这样做gui.setOnTouchListener(this);

Your activity class must implement OnTouchListener and override onTouch method. 您的活动类必须实现OnTouchListener并重写onTouch方法。

You can also Override onTouch in your custom view. 您也可以在自定义视图中覆盖onTouch。

There is no need to implement OnTouchListener in you GUI custom view class if you just override onTouch. 如果仅覆盖onTouch,则无需在GUI自定义视图类中实现OnTouchListener。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM