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

Как заставить текст исчезать и исчезать в Android?

У меня есть абзац текста, и когда нажимается кнопка, я хочу, чтобы текст исчезал, менялся на какой-то другой текст, а затем исчезал. У меня есть код, но он не делает анимацию с постепенным исчезновением исчезают.

    final TextView mSwitcher = (TextView) findViewById(R.id.bookContent);
    mSwitcher.setText("old text");

    final Animation in = new AlphaAnimation(0.0f, 1.0f);
    in.setDuration(3000);

    final Animation out = new AlphaAnimation(1.0f, 0.0f);
    out.setDuration(3000);

    Button moveOn = (Button) findViewById(R.id.moveOn);
    moveOn.setOnClickListener( new OnClickListener() {
        public void onClick(View v) {

            mSwitcher.startAnimation(out);
            mSwitcher.setText("new text");
            mSwitcher.startAnimation(in);

        }
    });
4b9b3361

Ответ 1

Кажется, вы настраиваете анимацию сразу после того, как вы ее отключили. Это делает только анимацию "in".

Чтобы начать вторую анимацию сразу после первого, вы можете добавить слушателя к своей первой анимации:

out.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationEnd(Animation animation) {
        mSwitcher.setText("New Text");
        mSwitcher.startAnimation(in);

    }
});

Затем в вашем методе onClick():

public void onClick(View v) {

    mSwitcher.startAnimation(out);

}

Это должно сделать трюк.


Другой подход - использовать AnimationSet.

final Animation in = new AlphaAnimation(0.0f, 1.0f);
in.setDuration(3000);

final Animation out = new AlphaAnimation(1.0f, 0.0f);
out.setDuration(3000);

AnimationSet as = new AnimationSet(true);
as.addAnimation(out);
in.setStartOffset(3000);
as.addAnimation(in);

Затем вместо запуска out запустите as.

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

Ответ 2

Если вы хотите использовать Animation, вы можете использовать AnimatorListener для прослушивания, когда выполняется первая анимация, а затем запустить вторую анимацию. Это будет onAnimationEnd().

Дополнительная информация доступна здесь: http://developer.android.com/reference/android/animation/Animator.AnimatorListener.html

Там может быть лучший способ сделать это с помощью AnimationSet, но это работает точно.

Ответ 3

Вам следует использовать что-то вроде TextSwitcher. В документации по Android есть документ на TextSwitcher. То, что я бы рекомендовал лучше всего, это посмотреть на API Demos, есть большой и простой в использовании один из TextSwitcher s. Скачайте API Demos и проверьте их самостоятельно или посмотрите здесь.

Ответ 4

чтобы добавить в eboix ответ... вот как я исчезаю в тексте и исчезаю текст, с задержкой между каждым исчезновением и до исчезновения, (сразу же после затухания).

Мой XML выглядит так.          

    <TextView
     android:id="@+id/textView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center_horizontal"
     android:gravity="center"
     android:text="Retrieving Result"
     android:textColor="@color/general_app_colour"
     android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
     android:id="@+id/blobText"
     android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="Please Wait" />

</LinearLayout>

Вы используете эти переменные в своей деятельности/фрагменте/диалоговом фрагменте, следующие переменные, которые я использовал в моей...

public class Loading_Dialog extends DialogFragment {
    public String[] text = new String[]{""};
    TextView blobText;
    Animation inAnimation;
    Animation displayLength;
    Animation delayAnimation;
    Animation outAnimation;
    //duration for fade effects
    int fadeEffectDuration = 700;
    //duration for delay between fadeout and fadein
    int delayDuration = 1000;
    int displayFor = 2000;
    public String[] text = new String[]{""};

Теперь объекты и переменные являются инициализированными, используются так, я использовал это для моего фрагмента диалога в методе oncreateDialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    final Dialog dialog = new Dialog(getActivity(),R.style.LoadingDialogAnimation);
dialog.getWindow().setContentView(R.layout.dialog_loading);
blobText = (TextView) dialog.findViewById(R.id.blobText);
    inAnimation = new AlphaAnimation(0f, 1f);
    inAnimation.setDuration(fadeEffectDuration);        
    displayLength = new AlphaAnimation(1f, 1f);
    displayLength.setDuration(displayFor);
    delayAnimation = new AlphaAnimation(0f, 0f);
    delayAnimation.setDuration(delayDuration);
    outAnimation = new AlphaAnimation(1f, 0f);
    outAnimation.setDuration(fadeEffectDuration);
    inAnimation.setAnimationListener(new AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {
        position++;
    if(position>=text.length)
    {
        position = 0;
    }
    blobText.setText(text[position]);
}           
@Override
public void onAnimationRepeat(Animation animation) {}           
@Override
public void onAnimationEnd(Animation animation) {
    blobText.startAnimation(displayLength);
}
});

displayLength.setAnimationListener(new AnimationListener() {

@Override
public void onAnimationStart(Animation animation) {
    // TODO Auto-generated method stub

 }

@Override
public void onAnimationRepeat(Animation animation) {
   // TODO Auto-generated method stub

 }

@Override
public void onAnimationEnd(Animation animation) {
    // TODO Auto-generated method stub
    blobText.startAnimation(outAnimation);  
}
});

    outAnimation.setAnimationListener(new AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        // TODO Auto-generated method stub
        blobText.startAnimation(delayAnimation);    
    }
    });
    delayAnimation.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) {
    // TODO Auto-generated method stub
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
    // TODO Auto-generated method stub

    }

@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
    blobText.startAnimation(inAnimation);
}
});

blobText.startAnimation(outAnimation);

Ответ 5

Когда у меня есть количество текстов для FadeIn/FadeOut, я предпочитаю использовать функцию для этого:

protected void onCreate(Bundle savedInstanceState) {
{
...
//Declare the array of texts:
String aSentences[]={"Sentence 1", "Sentence 2", "<b><i>Sentence 3</i></b>"};
TextView tView = (TextView)findViewById(R.id.Name_TextView_Object);

//call the function:
animateText(tView,aSentences,0,false);
}

private void animateText(final TextView textView, final String texts[], final int textIndex, final boolean forever) {
        //textView <-- The View which displays the texts
        //texts[] <-- Holds R references to the texts to display
        //textIndex <-- index of the first text to show in texts[]
        //forever <-- If equals true then after the last text it starts all over again with the first text resulting in an infinite loop. You have been warned.

        int fadeInDuration = 1000; // Configure time values here
        int timeBetween = 5000;
        int fadeOutDuration = 2000;

        textView.setVisibility(View.INVISIBLE);    //Visible or invisible by default - this will apply when the animation ends
        textView.setText(Html.fromHtml(texts[textIndex]));

        Animation fadeIn = new AlphaAnimation(0, 1);
        fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
        fadeIn.setDuration(fadeInDuration);

        Animation fadeOut = new AlphaAnimation(1, 0);
        fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
        fadeOut.setStartOffset(fadeInDuration + timeBetween);
        fadeOut.setDuration(fadeOutDuration);

        AnimationSet animation = new AnimationSet(false); // change to false
        animation.addAnimation(fadeIn);
        if((texts.length-1) != textIndex) animation.addAnimation(fadeOut);
        animation.setRepeatCount(1);
        textView.setAnimation(animation);

        animation.setAnimationListener(new Animation.AnimationListener() {
            public void onAnimationEnd(Animation animation) {
                if (texts.length -1 > textIndex) {
                    animateText(textView, texts, textIndex + 1,forever); //Calls itself until it gets to the end of the array
                }
                else {
                    textView.setVisibility(View.VISIBLE);
                    if (forever == true){
                        animateText(textView, texts, 0,forever);  //Calls itself to start the animation all over again in a loop if forever = true
                    }
                    else
                        {//do something when the end is reached}
                }
            }
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub
            }
            public void onAnimationStart(Animation animation) {
                // TODO Auto-generated method stub
            }
        });
    }