简体   繁体   中英

OnTouchListener in a View - Android

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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