Другое решение состоит в том, чтобы выполнить код через последовательный исполнитель nsynjs .
nsynjs будет последовательно оценивать все обещания и ставить обещания результат в свойство data
:
function synchronousCode() {
var getURL = function(url) {
return window.fetch(url).data.text().data;
};
var url = 'https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js';
console.log('received bytes:',getURL(url).length);
};
nsynjs.run(synchronousCode,{},function(){
console.log('synchronousCode done');
});
Шаг 1. Wrap с обратным вызовом в оболочку, совместимую с nsynjs (если у нее есть обещанная версия, вы можете пропустить этот тест):
var ajaxGet = function (ctx,url) {
var res = {};
var ex;
$.ajax(url)
.done(function (data) {
res.data = data;
})
.fail(function(e) {
ex = e;
})
.always(function() {
ctx.resume(ex);
});
return res;
};
ajaxGet.nsynjsHasCallback = true;
Шаг 2. Вставить синхронную логику в функцию:
function process() {
console.log('got data:', ajaxGet(nsynjsCtx, "data/file1.json").data);
}
Шаг 3. Выполнить функцию синхронно через nnsynjs:
nsynjs.run(process,this,function () {
console.log("synchronous function finished");
});
Nsynjs будет оценивать все операторы и выражения шаг за шагом, приостанавливая выполнение в случае, если результат некоторой медленной функции не готов.
Дополнительные примеры здесь: https://github.com/amaksr/nsynjs/tree/master/examples
Выяснил мою собственную проблему. Решение оказалось основано на интерполяторах.
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
fadeIn.setDuration(1000);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);
AnimationSet animation = new AnimationSet(false); //change to false
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);
Я знаю, что на это уже был дан ответ, но .....
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1000"
android:repeatCount="infinite"
android:repeatMode="reverse"
/>
Быстрый и простой способ быстро затухать и выходить с повторением. Наслаждайтесь
EDIT: в своей деятельности добавьте это:
yourView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.yourAnimation));
Вот что я использовал, чтобы исчезать в / из Views, надеюсь, что это кому-то поможет.
private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
AnimatorSet mAnimationSet = new AnimatorSet();
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA, 1f, 0f);
fadeOut.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
fadeOutTarget.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
fadeOut.setInterpolator(new LinearInterpolator());
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
fadeIn.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
fadeInTarget.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {}
@Override
public void onAnimationCancel(Animator animation) {}
@Override
public void onAnimationRepeat(Animator animation) {}
});
fadeIn.setInterpolator(new LinearInterpolator());
mAnimationSet.setDuration(duration);
mAnimationSet.playTogether(fadeOut, fadeIn);
mAnimationSet.start();
}
Поскольку я верю в силу XML (для макетов), это эквивалент принятого ответа , но исключительно как ресурс анимации:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/accelerate_decelerate"
android:fillAfter="true">
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="1000" />
<alpha
android:fromAlpha="1"
android:toAlpha="0"
android:duration="1000"
android:startOffset="1000"/>
</set>
fillAfter
- для того, чтобы исчезновение исчезло после завершения анимации. interpolator
обрабатывает интерполяцию анимаций, как вы можете догадаться. Вы также можете использовать другие типы интерполяторов, такие как Linear или Overshoot.
Обязательно запустите анимацию в своем представлении:
yourView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.fade));
Другая альтернатива:
Не нужно определять 2 анимации для fadeIn и fadeOut. fadeOut - это реверс fadeIn.
Итак, вы можете сделать это с помощью Animation.REVERSE следующим образом:
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);
then onAnimationEnd:
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
//TODO: Run when animation start
}
@Override
public void onAnimationEnd(Animation animation) {
//TODO: Run when animation end
}
@Override
public void onAnimationRepeat(Animation animation) {
//TODO: Run when animation repeat
}
});
Если вы используете Animator для создания анимации, вы можете
anim (каталог) -> fade_out.xml
<?xml version="1.0" encoding="UTF-8"?>
<objectAnimator
android:propertyName="alpha"
android:valueFrom="0"
android:valueTo="1"
xmlns:android="http://schemas.android.com/apk/res/android"/>
В java
Animator animator = AnimatorInflater.loadAnimator(context, R.animator.fade_out);
animator.setTarget(the_view_you_want_to_animation);
animator.setDuration(1000);
animator.start();
Другой способ заставить анимацию исчезать только с помощью java-кода:
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(the_view_you_want_to_animation, "alpha", 1f, 0);
fadeOut.setDuration(2000);
fadeOut.start();
Анимационные наборы не работают, как ожидалось. В конце концов я сдался и использовал класс postDelayed () класса Handler для анимации последовательности.
Вот мое решение, использующее AnimatorSet, которое кажется немного более надежным, чем AnimationSet.
// Custom animation on image
ImageView myView = (ImageView)splashDialog.findViewById(R.id.splashscreenImage);
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(myView, "alpha", 1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(myView, "alpha", .3f, 1f);
fadeIn.setDuration(2000);
final AnimatorSet mAnimationSet = new AnimatorSet();
mAnimationSet.play(fadeIn).after(fadeOut);
mAnimationSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnimationSet.start();
}
});
mAnimationSet.start();
viewToAnimate.animate().alpha(1).setDuration(1000).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
@Override
public void run() {
viewToAnimate.animate().alpha(0).setDuration(1000).setInterpolator(new AccelerateInterpolator()).start();
}
}).start();
Вы также можете использовать animationListener, что-то вроде этого:
fadeIn.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
this.startAnimation(fadeout);
}
});