好吧,我找到了解决方案。请注意,这只是一个解决方案,不一定是最佳解决方案。
我的解决方案是忽略所有逻辑事件(如 onScroll 或 onAnimationEnd,因为我无法让它们中的任何一个工作),并监听子视图位置的变化。当子视图静止时,动画就结束了。
这样做的一个实际好处是它适用于拖动和投掷。
一个问题是 onItemSelected 函数将从您的 UI 线程之外的另一个线程调用。通过使用活动的 runOnUIThread 函数来解决这个问题,如示例中所示。
监听变化的方式(注意这不是常规的onItemSelected函数,而是我自己的onItemReallySelected):
galArt.setOnItemReallySelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
_activity.runOnUiThread(new Runnable() {
public void run() {
//Do your stuff here ...
}
});
}
public void onNothingSelected(AdapterView<?> arg0) {
//... or here.
}
});
我的 Android Gallery 的实现:
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Gallery;
public class ArtGallery extends Gallery {
OnItemSelectedListener _listener;
Timer _timer = new Timer();
public ArtGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ArtGallery(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ArtGallery(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_UP){
setTimer();
}
return super.onTouchEvent(event);
}
private int _lastScrollX = Integer.MIN_VALUE;
private void setTimer() {
//Cancel existing tasks (if any), and create a new timer.
_timer.cancel();
_timer = new Timer();
//Schedule our animation check.
_timer.schedule(new TimerTask() {
@Override
public void run() {
//Just some value that will change while the animation is running.
int x = getSelectedView().getLeft();
if(_lastScrollX != x){
//Value has changed; save current value, and reset the timer.
_lastScrollX = x;
setTimer();
}else{
//The value hasn't changed during the last 50ms. That probably means that the animation has stopped.
fireOnSelected();
}
}
}, 50);
}
public void setOnItemReallySelectedListener(OnItemSelectedListener listener){
_listener = listener;
}
//This function is copied from the Android Gallery source code, and works exactly like the original one.
private void fireOnSelected() {
if (_listener == null)
return;
int selection = this.getSelectedItemPosition();
if (selection >= 0) {
_listener.onItemSelected(this, getSelectedView(), selection, getAdapter().getItemId(selection));
} else {
_listener.onNothingSelected(this);
}
}
}