Всего здесь нет, поэтому простите мое невежество. Я нашел код, чтобы анимировать ImageView:Создание нескольких изображений анимировать последовательно
public void startAnimatedBackground(Integer num) {
ImageSwitcher imageSwitcher = null;
switch (num) {
case 0:
imageSwitcher = img_0;
break;
case 1:
imageSwitcher = img_1;
break;
case 2:
imageSwitcher = img_2;
break;
case 3:
imageSwitcher = img_3;
break;
default:
break;
}
imageSwitcher.setInAnimation(aniIn);
imageSwitcher.setOutAnimation(aniOut);
imageSwitcher.setFactory(this);
imageSwitcher.setImageResource(images[index]);
final Handler handler = new Handler();
final ImageSwitcher finalImageSwitcher = imageSwitcher;
Runnable runnable = new Runnable() {
@Override
public void run() {
if (isRunning) {
index++;
index = index % images.length;
finalImageSwitcher.setImageResource(images[index]);
handler.postDelayed(this, interval);
}
}
};
handler.postDelayed(runnable, interval);
}
public View makeView() {
ImageView imageView = new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
return imageView;
}
@Override
public void finish() {
isRunning = false;
super.finish();
}}
Я создаю некоторые из необходимого кода на OnCreate():
private int index = 0;
private boolean isRunning = true;
Animation aniIn;
Animation aniOut;
ImageSwitcher img_0,img_1,img_2,img_3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_walk_in_progress);
aniIn = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
aniOut = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
aniIn.setDuration(500);
aniOut.setDuration(500);
img_0 = (ImageSwitcher) findViewById(R.id.switcher_accept);
img_1 = (ImageSwitcher) findViewById(R.id.switcher_on_way);
img_2 = (ImageSwitcher) findViewById(R.id.switcher_in_progress);
img_3 = (ImageSwitcher) findViewById(R.id.switcher_finished);
startAnimatedBackground(0);
}
Теперь первый один работает отлично. Теперь в действии я пытаюсь переключить это, чтобы анимация начала второго изображения:
Редактировать: Это новое «действие» не является тем, что раздувает представление. Новое мероприятие - это служба GCM Intent Service, которая просто прослушивает уведомления и обновляет информацию о моем уведомлении. Когда я получаю это уведомление, я хочу принять представление, которое в настоящее время отображается на экране пользователя уже, и обновить анимацию, чтобы переключить ее на 2-е изображение.
WalkInProgress walk = new WalkInProgress();
walk.startAnimatedBackground(1);
Это приводит к ошибке:
02-01 16:03:04.766 23805-24580/ly.leash.Leashly I/System.out﹕ null 02-01 16:03:04.778 23805-24580/ly.leash.Leashly E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[GcmIntentService] Process: ly.leash.Leashly, PID: 23805 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageSwitcher.setInAnimation(android.view.animation.Animation)' on a null object reference at ly.leash.Leashly.WalkInProgress.startAnimatedBackground(WalkInProgress.java:179) at ly.leash.Leashly.GcmIntentService.sendNotification(GcmIntentService.java:96) at ly.leash.Leashly.GcmIntentService.onHandleIntent(GcmIntentService.java:72) at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.os.HandlerThread.run(HandlerThread.java:61)
Так что для какой-либо причине анимация возвращается к нулевой.
Я попытался объявить все это в функции startAnimatedBackground вместо OnCreate, но это приводит к ошибкам, а также:
02-01 16:15:10.488 25553-25930/ly.leash.Leashly E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[GcmIntentService] Process: ly.leash.Leashly, PID: 25553 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.content.ContextWrapper.getResources(ContextWrapper.java:85) at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74) at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:73) at ly.leash.Leashly.WalkInProgress.startAnimatedBackground(WalkInProgress.java:152) at ly.leash.Leashly.GcmIntentService.sendNotification(GcmIntentService.java:96) at ly.leash.Leashly.GcmIntentService.onHandleIntent(GcmIntentService.java:72) at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.os.HandlerThread.run(HandlerThread.java:61)
Ошибка в этой строке:
aniIn = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
Что вы подразумеваете под 'Now в другой части приложения? Другая деятельность? – iRuth
Да, другое занятие. Извините – user1610719
Я предполагаю, что 'img_1' не находится в файле макета новой активности. Я прав? – iRuth