тряска, колебание просмотреть анимацию в Android
Я создал аним.xml-файл, такие как НИЖЕ, чтобы встряхнуть imageview, как IOS значок встряхивания в android.
Однако это не дает мне тот же результат.
Есть ли идея получше?
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromDegrees="-2"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="2" />
12 ответов:
попробуйте
android:repeatMode="reverse". Ниже анимация дает очень разумную имитацию на моем Galaxy Nexus. Очевидно, что вы можете точно настроить параметры по своему вкусу.<?xml version="1.0" encoding="utf-8"?> <rotate xmlns:android="http://schemas.android.com/apk/res/android" android:duration="100" android:fromDegrees="-5" android:pivotX="50%" android:pivotY="50%" android:repeatCount="infinite" android:repeatMode="reverse" android:toDegrees="5" />
вы можете попробовать это:
пожать.xml
<translate xmlns:android="http://schemas.android.com/apk/res/android" android:fromXDelta="0" android:toXDelta="10" android:duration="1000" android:interpolator="@anim/cycle_7" />cycle_7.xml
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="7" />
хорошая анимация встряхивания;
res / anim встряхнуть.mxl
<set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="150" android:fromXDelta="-10%" android:repeatCount="5" android:repeatMode="reverse" android:toXDelta="10%"/> </set>как использовать
final Animation animShake = AnimationUtils.loadAnimation(this, R.anim.shake); btn_done = (Button) findViewById(R.id.btn_act_confirm_done); btn_done.startAnimation(animShake);
попробуйте использовать этот:
<set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:duration="70" android:fromDegrees="-5" android:pivotX="50%" android:pivotY="50%" android:repeatCount="5" android:repeatMode="reverse" android:interpolator="@android:anim/linear_interpolator" android:toDegrees="5" /> <translate android:fromXDelta="-10" android:toXDelta="10" android:repeatCount="5" android:repeatMode="reverse" android:interpolator="@android:anim/linear_interpolator" android:duration="70" /> </set>
Я создал эффект встряхивания на Android и опубликовал в GitHub. Смотрите, если это работает лучше.
https://github.com/teoinke/ShakeAnimation
соответствующий код:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/overshoot_interpolator" android:fillAfter="true"> <translate android:startOffset="100" android:fromXDelta="0%p" android:toXDelta="10%p" android:duration="50" /> <translate android:startOffset="150" android:fromXDelta="0%p" android:toXDelta="-25%p" android:duration="110" /> <translate android:startOffset="260" android:fromXDelta="0%p" android:toXDelta="25%p" android:duration="120" /> <translate android:startOffset="380" android:fromXDelta="0%p" android:toXDelta="-20%p" android:duration="130" /> <translate android:startOffset="510" android:fromXDelta="0%p" android:toXDelta="10%p" android:duration="140" /> </set>
это работает довольно хорошо (хотя и не идеально) как iOS "неправильный PIN-код" встряхивания клон:
final float FREQ = 3f; final float DECAY = 2f; // interpolator that goes 1 -> -1 -> 1 -> -1 in a sine wave pattern. TimeInterpolator decayingSineWave = new TimeInterpolator() { @Override public float getInterpolation(float input) { double raw = Math.sin(FREQ * input * 2 * Math.PI); return (float)(raw * Math.exp(-input * DECAY)); } }; shakeField.animate() .xBy(-100) .setInterpolator(decayingSineWave) .setDuration(500) .start();
чтобы сделать эффект встряхивания, как это
сначала определите анимацию встряхивания внутри папки anim как shake.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:duration="70" android:fromDegrees="-5" android:interpolator="@android:anim/linear_interpolator" android:pivotX="50%" android:pivotY="50%" android:repeatCount="5" android:repeatMode="reverse" android:toDegrees="5" /> <translate android:duration="70" android:fromXDelta="-10" android:interpolator="@android:anim/linear_interpolator" android:repeatCount="5" android:repeatMode="reverse" android:toXDelta="10" /> </set>потом в коде
if (TextUtils.isEmpty(phone.getText()) || phone.getText().length() < 10) { //shake animation phone.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.shake)); }
Я создал очень хорошее приближение встряхивания iOS (когда вы долго нажимаете значок, чтобы удалить приложение с рабочего стола). Вы должны применить внутри вашего кода, программно, так как он требует генерации случайных чисел:
int dur1 = 70 + (int)(Math.random() * 30); int dur2 = 70 + (int)(Math.random() * 30); // Create an animation instance Animation an = new RotateAnimation(-3, 3, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); // Set the animation's parameters an.setDuration(dur1); // duration in ms an.setRepeatCount(-1); // -1 = infinite repeated an.setRepeatMode(Animation.REVERSE); an.setFillAfter(true); // keep rotation after animation // Create an animation instance Animation an2 = new TranslateAnimation(-TranslateAnimation.RELATIVE_TO_SELF,0.02f, TranslateAnimation.RELATIVE_TO_SELF,0.02f, -TranslateAnimation.RELATIVE_TO_SELF,0.02f, TranslateAnimation.RELATIVE_TO_SELF,0.02f); // Set the animation's parameters an2.setDuration(dur2); // duration in ms an2.setRepeatCount(-1); // -1 = infinite repeated an2.setRepeatMode(Animation.REVERSE); an2.setFillAfter(true); // keep rotation after animation AnimationSet s = new AnimationSet(false);//false means don't share interpolators s.addAnimation(an); s.addAnimation(an2); // Apply animation to image view itemView.setAnimation(s);этот код был разработан для применения внутри gridview адаптера (getView), но вы можете применить его к любому виду, изменив последнюю строку на:
yourViewName.setAnimations (s);
IOS wobble animation не так просто попытаться изменить pivot x и y случайным образом при вращении. Вы должны изменить значение программным путем. Может быть, вы также можете использовать перевод анимации одновременно
к сожалению, принятый ответ не будет работать отдельно от onCreateView фрагмента.
пример, если у вас есть метод onClick и внутри него. У вас есть анимация, как показано ниже, она не будет работать.
пожалуйста, пройдите через код.
DoneStart.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { register(view); } });метод регистрации имеет некоторые проверки, как показано ниже код
private void register(View view) { String type = typedThings.getText.toString(); String km = Km_Now.getText().toString(); if (serviceType == null) { animationServiceList = AnimationUtils.loadAnimation(getActivity(), R.anim.shake_wobble); silverServiceButton.setAnimation(animationServiceList); generalServiceButton.setAnimation(animationServiceList); platinumServiceButton.setAnimation(animationServiceList); animationServiceList.start(); } else if (km == null) { animationEditText = AnimationUtils.loadAnimation(getActivity(), R.anim.shake_wobble); Km_Now.setAnimation(animationEditText); animationEditText.start(); }вызов animationServiceList.начать(); никогда не будет называться,
решение: используйте PropertyAnimator как ObjectAnimator.
другие ответы также верны, но это немного более гладко, чем они, так как он использует интерполятор производит гладкие числа для движения назад вперед
public class WobblyView extends ImageView implements ValueAnimator.AnimatorUpdateListener { private final ValueAnimator va = ValueAnimator.ofInt(-10, 10); public WobblyView(Context context) { this(context, null); } public WobblyView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public WobblyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setAdjustViewBounds(true); setImageResource(R.drawable.ic_logo); va.setInterpolator(new AccelerateDecelerateInterpolator()); va.setRepeatMode(ValueAnimator.REVERSE); va.setRepeatCount(ValueAnimator.INFINITE); va.setDuration(1000); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); va.addUpdateListener(this); va.start(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); va.removeUpdateListener(this); } @Override public void onAnimationUpdate(ValueAnimator animation) { int heading = (int) animation.getAnimatedValue(); setRotation(heading); } }
/** * * @param view view that will be animated * @param duration for how long in ms will it shake * @param offset start offset of the animation * @return returns the same view with animation properties */ public static View makeMeShake(View view, int duration, int offset) { Animation anim = new TranslateAnimation(-offset,offset,0,0); anim.setDuration(duration); anim.setRepeatMode(Animation.REVERSE); anim.setRepeatCount(5); view.startAnimation(anim); return view; }использование:
TextView tv; makeMeShake(tv,20,5); // it will shake quite fast

Comments