patternjavaMinor
Passing listener to customized extended View in Android
Viewed 0 times
androidcustomizedpassingextendedviewlistener
Problem
I extended
This code works fine but I'm new to Android and somehow I'm not sure I did it the proper way so I'm asking for a code review.
Do I have to save the callback in member variable?
I couldn't access
NumberPicker with several methods needed in my application. When I came to defining a OnValueChangeListener this is how I did it:import android.widget.NumberPicker;
interface ValueChangeCallback {
public void execute(RemListView list, int oldVal, int newVal);
}
public class RemListView extends NumberPicker {
ValueChangeCallback mValueChangeCallback;
RemListView thisList = this;
public void setValueChangeCallback(ValueChangeCallback callback) {
mValueChangeCallback = callback;
setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mValueChangeCallback.execute(thisList, oldVal, newVal);
}
});
}
}This code works fine but I'm new to Android and somehow I'm not sure I did it the proper way so I'm asking for a code review.
Do I have to save the callback in member variable?
I couldn't access
this from within callback so I introduced thisList variable. Can it be avoided?Solution
I think you have missed the point with the NumberPicker here. There is no need to add in a new level of abstraction for your application.
Right now your 'calling' code needs to implement a
Sure, this works, but, the design is supposed to be a whole lot simpler, just do:
Make your calling code implement a
Basically, your code should be simplified to:
and your calling class should be changed to have a
Oh, and since your RemListView class is now empty, unless you have other stuff in there, you may as well delete the class and use NumberPicker directly.
Right now your 'calling' code needs to implement a
ValueChangeCallback class, and call setValueChangeCallback(callback). The ValueChangeCallback needs to implement the execute() method.Sure, this works, but, the design is supposed to be a whole lot simpler, just do:
Make your calling code implement a
NumberPicker.OnValueChangeListener and the onValueChange() method. Then, it can call setOnValueChangedListener directly.Basically, your code should be simplified to:
import android.widget.NumberPicker;
public class RemListView extends NumberPicker {
}and your calling class should be changed to have a
NumberPicker.OnValueChangeListener instance instead of a ValueChangeCallback instance, and, well, that's it.Oh, and since your RemListView class is now empty, unless you have other stuff in there, you may as well delete the class and use NumberPicker directly.
Code Snippets
import android.widget.NumberPicker;
public class RemListView extends NumberPicker {
}Context
StackExchange Code Review Q#55734, answer score: 5
Revisions (0)
No revisions yet.