Reputation: 3804
This is an Android project but the question is more related to JAVA itself.
I'm trying to override a method in an Activity
but I want this method to run different code based on two conditions: if a user is logged in and what type of user.
The method I'm overriding is the dispatchTouchEvent
which is called, at least one time, every time the user touches the screen.
I could put the conditions inside the method however as a mention earlier, this is a method that is called a lot so I was trying to avoid doing extra logic over and over on it.
Ideally I wanted something like this:
if (isUserLogged) {
if (user.getType == 'A') {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (//condition based on ev)
return super.dispatchTouchEvent(ev);
else
return true;
}
}
else {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (//different condition based on ev)
return super.dispatchTouchEvent(ev);
else
return true;
}
}
}
Of course this is not possible.
Any tips on how I could avoid putting all the code inside the method?
Upvotes: 2
Views: 1549
Reputation: 1468
While I'm sure you know this is not possible, something similar is possible and quite possibility what you want. Maybe just using an if/switch inside your onCall()
method and then call an appropriate method.
Example
public void onTouch(SomeEvent e){
if(a){
methodA();
} else if (b) {
methodB();
}
}
void methodA ();//for simplicity
void methodB ();
Upvotes: 1
Reputation: 2720
You can create different implementations of an interface which shares the dispatchTouchEvent
method. Take a look at the Strategy Pattern.
Upvotes: 3