OnTouchListener in a View - Android

五迷三道 提交于 2019-12-13 16:00:31

问题


When I am adding a listener 'OnTouchListener' to a View, it doesn't register. 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?

I let the GUI class implement OnTouchListener and adds a OnTouch method... But I put

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

In the OnTouch method, yet it doesn't log that at all.


回答1:


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

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.

If you do this gui.setOnTouchListener(this);

Your activity class must implement OnTouchListener and override onTouch method.

You can also Override onTouch in your custom view.

There is no need to implement OnTouchListener in you GUI custom view class if you just override onTouch.



来源:https://stackoverflow.com/questions/16506287/ontouchlistener-in-a-view-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!