Подтвердить что ты не робот

Как заставить моргнуть текстовое изображение

Ребята, у меня есть текстовое представление, которое мне нужно, чтобы оно мигало, пожалуйста, помогите мне с ним.

<TextView 
       android:id="@+id/usage"
       android:layout_marginTop="220dip"
       android:layout_marginLeft="45dip"
       android:layout_marginRight="15dip"
       android:typeface="serif"            
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Google "
       android:textColor="#030900"/>

Я хочу, чтобы текст google мигал

4b9b3361

Ответ 1

Это устаревший ответ на Android до версии 3.0, пожалуйста, используйте ответ SolArabehety или посмотрите этот поток.

Оригинальный ответ

package teste.blink;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

public class TesteBlinkActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        blink();
}

private void blink(){
    final Handler handler = new Handler();
    new Thread(new Runnable() {
        @Override
        public void run() {
        int timeToBlink = 1000;    //in milissegunds
        try{Thread.sleep(timeToBlink);}catch (Exception e) {}
            handler.post(new Runnable() {
                @Override
                    public void run() {
                    TextView txt = (TextView) findViewById(R.id.usage);
                    if(txt.getVisibility() == View.VISIBLE){
                        txt.setVisibility(View.INVISIBLE);
                    }else{
                        txt.setVisibility(View.VISIBLE);
                    }
                    blink();
                }
                });
            }
        }).start();
    }

<TextView 
   android:id="@+id/usage"
   android:layout_marginTop="220dip"
   android:layout_marginLeft="45dip"
   android:layout_marginRight="15dip"
   android:typeface="serif"            
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Google "
   android:textColor="#030900"/>

Ответ 2

Вы можете использовать это:

TextView myText = (TextView) findViewById(R.id.myText );

Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(50); //You can manage the blinking time with this parameter
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
myText.startAnimation(anim);

Это тот же ответ, который я дал в этом сообщении Мигающий текст в представлении android

Надеюсь, это поможет!

Ответ 3

Используйте XML-анимации для этой цели:

R.anim.blink

<?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>

Активность blink: используйте его следующим образом: -

public class BlinkActivity extends Activity implements AnimationListener {

    TextView txtMessage;
    Button btnStart;

    // Animation
    Animation animBlink;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blink);

        txtMessage = (TextView) findViewById(R.id.txtMessage);
        btnStart = (Button) findViewById(R.id.btnStart);

        // load the animation
        animBlink = AnimationUtils.loadAnimation(this,
                R.anim.blink);

        // set animation listener
        animBlink.setAnimationListener(this);

        // button click event
        btnStart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                txtMessage.setVisibility(View.VISIBLE);

                // start the animation
                txtMessage.startAnimation(animBlink);
            }
        });

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        // Take any action after completing the animation

        // check for blink animation
        if (animation == animBlink) {
        }

    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

}

Сообщите мне, есть ли у вас какие-либо вопросы.

Ответ 4

Создайте AlphaAnimation и примените его к текстовому виду в действии, где вы настраиваете текстовое представление. Мигание будет выполнено путем повторения анимации от 1.0 alpha до 0.0 alpha до 1.0 alpha.


Изменить: Google предоставляет.

Ответ 5

Не нужно устанавливать для этого. Просто альфа:

анит/flash_leave_now.xml

    <?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:duration="900"
       android:fromAlpha="1.0"
       android:repeatCount="infinite"
       android:repeatMode="reverse"
       android:toAlpha="0.2"/>

И в коде:

mTextView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.flash_leave_now));

Ответ 6

Вы можете сделать анимацию или, может быть, почему бы не сделать ее View.VISIBLE и View.INVISIBLE с помощью таймера? Я думаю, что лучший способ - это анимация с альфой:)

Ответ 7

Вежливость к верхнему ответу, вот что я сделал:

 textBlink = new TimerTask() {
        int countdown = 10;

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (countdown <= 0) {
                        timer.cancel();
                        textview.setVisibility(View.GONE);
                    } else {
                            textview.setVisibility(textview.getVisibility() == View.VISIBLE?View.GONE:View.VISIBLE);
                        countdown--;
                    }
                }
            });
        }
    };

тогда где-то в коде:

  timer = new Timer();
  timer.scheduleAtFixedRate(textBlink,0,500);

Это сделает эффект моргания в течение 5 секунд. Рекомендуется, если вы не хотите использовать эффект fadeIn-fadeOut.

Ответ 8

private fun blink() {
        val handler = Handler()
        Thread(Runnable {
            val timeToBlink = 500    //in milissegunds
            try {
                Thread.sleep(timeToBlink.toLong())
            } catch (e: Exception) {
            }

            handler.post(Runnable {

                if (usage.visibility == View.VISIBLE) {
                    usage.visibility = View.INVISIBLE
                } else {
                    usage.visibility = View.VISIBLE
                }
                blink()
            })
        }).start()
    }

Ответ 9

public final class BlinkEffectUtils {

    private static BlinkEffectUtils blinkEffect;

    public enum PROPERTY_TYPE {
        BACKGROUND_COLOR,
        TEXT_COLOR
    }

    private BlinkEffectUtils() {
    }

    public static BlinkEffectUtils getInstance(Context context) {
        if (blinkEffect == null) {
            blinkEffect = new BlinkEffectUtils();
        }

        return blinkEffect;
    }

    public void setBlinkEffect(Object targetView, PROPERTY_TYPE property_type, int duration, int defaultColor, int effectColor) {
        String propertyName = "";

        switch (property_type) {

            case TEXT_COLOR:
                propertyName = "textColor";
                break;

            case BACKGROUND_COLOR:
                propertyName = "backgroundColor";
                break;
        }

        @SuppressLint("ObjectAnimatorBinding")
        ObjectAnimator anim = ObjectAnimator.ofInt(targetView, propertyName,
                effectColor,
                defaultColor);
        anim.setDuration(duration);
        anim.setEvaluator(new ArgbEvaluator());
        anim.setRepeatMode(ValueAnimator.REVERSE);
        anim.setRepeatCount(ValueAnimator.INFINITE);
        anim.start();

    }

}

Ответ 10

Просто используйте <blink/>.

<blink
     android:layout_width="wrap_content"
     android:layout_height="wrap_content">

  <TextView 
       android:id="@+id/usage"
       android:layout_marginTop="220dip"
       android:layout_marginLeft="45dip"
       android:layout_marginRight="15dip"
       android:typeface="serif"            
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Google "
       android:textColor="#030900"/>

</blink>

Ответ 11

Вот моя вспомогательная реализация с использованием альфа-анимации:

    public void blinkText(final TextView text_to_animate, int durationMillis) {

        final AlphaAnimation fade_out = new AlphaAnimation(1.0f, 0.0f);
        //ScaleAnimation scale_it = new ScaleAnimation(1.0f, 1.25f, 1.0f, 1.25f);
        fade_out.setDuration(durationMillis);

        final AlphaAnimation fade_in = new AlphaAnimation(0.0f, 1.0f);
        //ScaleAnimation scale_it = new ScaleAnimation(1.0f, 1.25f, 1.0f, 1.25f);
        fade_in.setDuration(durationMillis);

        fade_out.setAnimationListener(new AnimationListener() {
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
            if (recording == true)
                text_to_animate.startAnimation(fade_in);
            }
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub              
            }

            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub              
            }

        });

        fade_in.setAnimationListener(new AnimationListener() {
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                if (recording == true)
                    text_to_animate.startAnimation(fade_out);
            }
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub              
            }

            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub              
            }

        });

        text_to_animate.startAnimation(fade_out);       

    }