Android - Как заставить текст кнопки мигать / мигать?

У меня есть вопрос, похожий на этот, но я хочу, чтобы только текст на кнопке мигал. Я не хочу, чтобы фон кнопки также мигал.

Это мой файл R.anim.blink.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0"
           android:toAlpha="1.0"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:duration="500"
           android:startOffset="20"
           android:repeatMode="reverse"
           android:repeatCount="infinite"/>
</set>

Но этот код...

Animation blinkingAnimation = AnimationUtils.loadAnimation(this, R.anim.blink);
myButton.setAnimation(blinkingAnimation);

... заставляет мигать всю кнопку Так как заставить мигать только текст (чтобы фон кнопки показывался постоянно)?

5 ответов

Простой способ:

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button btn = (Button) findViewById(R.id.btn);
    final ObjectAnimator colorAnim = ObjectAnimator.ofInt(btn, "textColor", Color.BLACK, Color.TRANSPARENT); //you can change colors
    colorAnim.setDuration(500); //duration of flash
    colorAnim.setEvaluator(new ArgbEvaluator());
    colorAnim.setRepeatCount(ValueAnimator.INFINITE);
    colorAnim.setRepeatMode(ValueAnimator.REVERSE);
    colorAnim.start();


    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            colorAnim.end();
            colorAnim.cancel();
        }
    });
}

Он будет мигать после нажатия.

РЕДАКТИРОВАТЬ:

Вы можете определить свою анимацию в xml (используйте objectAnimator):

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="textColor"
    android:duration="500"
    android:valueFrom="#000000"
    android:valueTo="@android:color/transparent"
    android:repeatMode="reverse"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/accelerate_interpolator" />

и используйте его в своем коде:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    final ObjectAnimator animator = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.blink);
    final Button btn = (Button) findViewById(R.id.btn);
    animator.setTarget(btn);
    animator.start();

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            animator.end();
            animator.cancel();
        }
    });
}

XML должен находиться в папке "аниматор".

Попробуйте этот код в методе Activity

    final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
    animation.setDuration(500); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in
    final Button btn = (Button) findViewById(R.id.your_btn);
    btn.startAnimation(animation);
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View view) {
            view.clearAnimation();
            //also your extra work here
        }
    });

Я предлагаю вам использовать FrameLayout вместо.

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:background="any color" >

    <TextView
        android:id="@+id/bn1"
        android:layout_width="wrap_content"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_height="wrap_content"
        android:text="some_txt"/>

</FrameLayout>

Теперь примените Blink Animation, которая TextView

в котлине мы можем это сделать. мигает элемент res \ animator\blink.xml

      <?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="alpha"
    android:duration="1000"
    android:valueFrom="1.0"
    android:valueTo="0.1"
    android:repeatMode="reverse"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/accelerate_interpolator" /> 

в activity.kt

        lateinit var animator : ObjectAnimator

onCreate

      animator = AnimatorInflater.loadAnimator(this, R.animator.blink) as ObjectAnimator
animator.target = targetElement
animator.start()

остановить и отменить

      animator.end()
animator.cancel()
targetElement?.alpha = 1.0f

↓↓↓↓↓↓ ↓↓↓↓

мигать только текст

      val valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f)
valueAnimator.duration = 1000
valueAnimator.repeatCount = ValueAnimator.INFINITE
valueAnimator.repeatMode = ValueAnimator.REVERSE
    valueAnimator.addUpdateListener { it ->
    val fractionAnim = it.animatedValue as Float
    targetElement?.setTextColor(
        ColorUtils.blendARGB(Color.parseColor("#00cc00"),
        resources.getColor(R.color.transparent), fractionAnim))
    }
valueAnimator.start()

targetElement?.setOnClickListener{
    valueAnimator.cancel()
    targetElement?.setTextColor(Color.parseColor("#00cc00"))
}

blink_effect.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="600"
        android:repeatMode="reverse"
        android:repeatCount="infinite"/>
</set>

MainActivity.java

 Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
                        R.anim.blink_effect);
 yourWidget.startAnimation(animation1);
Другие вопросы по тегам