user4320567
user4320567

Reputation:

How to call onTouch() method

I would like please to call onTouch() method which is in different class than the method onOptionsItemSelected() I want to call from, here's the code:

public boolean onTouch(View v, MotionEvent event) {
             float downx = 0, downy = 0, upx = 0, upy = 0;
            int action = event.getAction();
            switch (action) {
            case MotionEvent.ACTION_DOWN:
              downx = event.getX();
              downy = event.getY();
              break;
            case MotionEvent.ACTION_MOVE:
              break;
            case MotionEvent.ACTION_UP:
              upx = event.getX();
              upy = event.getY();
              mCanvas.drawLine(downx, downy, upx, upy, mPaint);
              invalidate();
              break;
            case MotionEvent.ACTION_CANCEL:
              break;
            default:
              break;
            }
            return true;
          }

The method that I wanted to call onTouch() from:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.LINE_ID:
            //i want to call it here            
            return true;

onOptionsItemSelected() is in MainClass but onTouch() is in a subclass of MainClass.

How i can do that? how i can call drawLine()?

UPDATE:

I tried :

View v = null; MotionEvent event = null;
            MyView sub_class = new MyView(getBaseContext());
            sub_class.onTouch(v, event);

but it's crashed! Any Help please! I think this is very easy for some ppl.. They don't care :(

Upvotes: 2

Views: 2174

Answers (2)

abhi
abhi

Reputation: 1444

Though you should not call Android View's internal methods which are invoked by the OS itself. However, you can still do this by simply creating an instance on the sub-class and invoking the onTouch method through this object. Check the code below:

SubClass sub_class = new SubClass();
sub_class.onTouch(v, event);

Upvotes: 0

chiastic-security
chiastic-security

Reputation: 20520

You really shouldn't be calling onTouch() at all. This is something that the Android system generates when there's a touch event, not something that you should be calling manually. If nothing else, how would you work out what MotionEvent to pass it?

What you need to do is to call whatever method your onTouch() method invokes when a touch event comes in. Refactor your onTouch() so that it calls a method, with appropriate parameters, that behaves appropriately when a touch event occurs; and then have your onOptionsItemSelected() call that method too.

Upvotes: 1

Related Questions