我正在尝试在应用小部件中添加视图翻转器。它必须通过滑动手势简单地在 2 个图像之间翻转。但是什么都没有显示并且它崩溃了。我有活动的代码,所以我翻译了类似的小部件并进行了适当的更改。但在某个地方,我错过了一些东西。请指导。这是代码。
public class WidgetFlipper extends AppWidgetProvider{
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private ViewFlipper vf;
private Context mContext;
private final GestureDetector detector = new GestureDetector(new MyGestureDetector());
public MyGestureDetector obj = new MyGestureDetector();
@SuppressLint("NewApi")
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int []appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
mContext = context;
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main);
vf.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(final View view, final MotionEvent event) {
detector.onTouchEvent(event);
return true;
}
});
views.setImageViewResource(R.id.vfShow, R.drawable.image1);
views.setImageViewResource(R.id.vfShow, R.drawable.image2);
Intent intent = new Intent ("android.appwidget.action.APPWIDGET_UPDATE");
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.vfShow, pendingIntent);
ComponentName myWidget=new ComponentName(context, WidgetFlipper.class);
AppWidgetManager manager=AppWidgetManager.getInstance(context);
manager.updateAppWidget(myWidget, views);
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
vf.setInAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.left_in));
vf.setOutAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.left_out));
vf.showNext();
return true;
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
vf.setInAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.right_in));
vf.setOutAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.right_out));
vf.showPrevious();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
}