简体   繁体   中英

Android OnTouchListener Does Not Work

It's simple. The OnTouchListener does not work at all.

I'm fairly certain it's being initialized. I'm using a custom view to draw my UI, and as usual, I'm being impeded by Android's touchy API (pun intended):

public class ViewInterface extends View implements OnTouchListener{

public ViewInterface(Context context){
    super(context);

    ...
}

public void update(){
    ...
}

@Override
public void onDraw(Canvas canvas){
    ...
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:
        keyboardEnabled = true;
        return true;
    case MotionEvent.ACTION_UP:
        keyboardEnabled = false;
        return true;
    default: break;
    }

    return false;
}

Code for initializing the view in the main activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    //setContentView(R.layout.activity_aidan);
    activity = this;

    viewInterface = new ViewInterface(this);
    setContentView(viewInterface);

    initializeSpeechRecognition();
    findMe();

    run.start();
}

What am I missing? Upon touching the screen and holding it, keyboardEnabled should be set to true (its just a debug value) - yet it does not do anything. The touch events don't seem to be responding at all.

I've attempted to use the onTouchEvent method built into View with the following code:

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:
        keyboardEnabled = true;
        return true;
    case MotionEvent.ACTION_UP:
        keyboardEnabled = false;
        return true;
    default: break;
    }

    return false;
}

However this did not work either. The touch events are not responding at all - tapping the screen and releasing should be setting keyboardEnabled to false - which it does not.

You should override the onTouchEvent() method of the View class.

Right now you are simply implementing the OnTouchListener interface which should be used in conjunction with the setOnTouchListener() method.

For example:

@Override
public boolean onTouchEvent(MotionEvent event) {
    // do whatever
}

Don't forget to call super where appropriate!

Alternatively, you could call setOnTouchListener(this); somewhere in your code, but that seems redundant.

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