想一想,我已经成功破解了这个难题。
策略如下:
- 图库中的所有项目都必须有一个 ViewAnimator 作为根。
- 扩展标准库,并覆盖 onKeyDown
- 确保在时间作业后使用库中的 onKeyDown,例如 gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0,0));
- 在扩展 Gallery 中捕获键时,获取当前 View,它是 ViewAnimator 的一个实例,从 Gallery 的适配器获取下一个视图,并为下一个视图创建动画
- 动画完成后,调用 setSelection(getSelectedItemPosition()+1); (需要检查是否有包装)
这是一个有效的早期概念证明,尽管它缺少一些检查。
<ViewAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/slideshow_animator"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
package com.elsewhat.slideshow.api;
public class CustomGallery extends Gallery implements AnimationListener {
boolean mDoTransition=false;
public CustomGallery(Context context) {
super(context);
}
public CustomGallery(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/*
* (non-Javadoc)
*
* @see android.widget.Gallery#onKeyDown(int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(mDoTransition==true){
//leave the transition to the super class
return super.onKeyDown(keyCode, event);
}else {
//handle the switch without transition ourselves
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
//to be implemented similar as below
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (getCount() > 0 && getSelectedItemPosition() < getCount() - 1) {
View currentView = getSelectedView();
View unboundNewView= getAdapter().getView(getSelectedItemPosition()+1, null, null);
ViewAnimator viewAnimator = (ViewAnimator)currentView;
Animation inAnimation = new AlphaAnimation(0.0f, 1.0f);
inAnimation.setDuration(1000);
inAnimation.setAnimationListener(this);
viewAnimator.setInAnimation(inAnimation);
Animation outAnimation = new AlphaAnimation(1.0f, 0.0f);
outAnimation.setDuration(1000);
viewAnimator.setOutAnimation(outAnimation);
viewAnimator.addView(unboundNewView);
viewAnimator.showNext();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
}
return super.onKeyDown(keyCode, event);
}
}
public void setDoTransition(boolean doTransition){
mDoTransition= doTransition;
}
public boolean getDoTransition(){
return mDoTransition;
}
@Override
public void onAnimationEnd(Animation arg0) {
setSelection(getSelectedItemPosition()+1);
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
}