如何在Textview,Android中添加CrossFade效果

时间:2014-02-25 20:09:07

标签: android string animation random

下面的代码从两个数组planet_array1和planet_array中获取一个数字,它也随机化了字符串。现在怎么能拿这两个字符串并添加交叉渐变或淡化效果?此代码也随机化但停止。如何添加持续时间,它会在几秒钟后自动更改字符串?我不想添加任何按钮来更改字符串。

package com.example.androidanimation;

import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class FadeInActivity extends Activity {


        String[] mTestArray;
        String[] mTestArray1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sample);

            mTestArray =   getResources().getStringArray(R.array.planets_array);
            mTestArray1 =   getResources().getStringArray(R.array.planets1_array);
        }

        @Override
        protected void onStart() {
            super.onStart();
            updateTextView();    
        }

        private void updateTextView() {
            TextView textView = (TextView)findViewById(R.id.randomTextView); 
            TextView textView1 = (TextView)findViewById(R.id.randomTextView1); 
            Random random = new Random();

            int maxIndex = mTestArray.length;
            int generatedIndex = random.nextInt(maxIndex);
            textView.setText(mTestArray[generatedIndex]);   
            textView1.setText(mTestArray1[generatedIndex]);  
        }
    }

sample.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
            android:id="@+id/randomTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"/>

    <TextView
        android:id="@+id/randomTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="163dp" />

</RelativeLayout>

planet_array

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>

</resources>

planet1_array

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets1_array">
        <item>Merc</item>
        <item>Ven</item>
        <item>Ear</item>
        <item>Mar</item>
    </string-array>

</resources>

最终工作输出

    public class MainActivity extends FragmentActivity {

    private TextSwitcher mSwitcher, mSwitcher1;
    private int mCounter = 0;
    String textToShow[] = {
            "Main HeadLine", "Your Message", "New In Technology", "New Articles", "Business News", "What IS New"
    };
    String textToShow1[] = {
            "Main HeadLine", "Your Message", "New In Technology", "New Articles", "Business News", "What IS New"
    };
    int messageCount = textToShow.length;
    // to keep current Index of text
    int currentIndex = -1;

    Timer timer = new Timer();

    public class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    updateTextView();
                }
            });
        }
    }

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

        mSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);
        mSwitcher1 = (TextSwitcher) findViewById(R.id.textSwitcher01);
        // BEGIN_INCLUDE(setup)
        // Set the factory used to create TextViews to switch between.
        mSwitcher.setFactory(mFactory);
        mSwitcher1.setFactory(mFactory);
        Animation in = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in);
        Animation out = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out);
        mSwitcher.setInAnimation(in);
        mSwitcher1.setInAnimation(in);
        mSwitcher.setOutAnimation(out);
        mSwitcher1.setOutAnimation(out);

    }

    @Override
    protected void onStart() {
        super.onStart();
        timer.schedule(new MyTimerTask(), 0, 1000);

    }

    private void updateTextView() {

        int maxIndex = textToShow.length;
        Random random = new Random();
        int generatedIndex = random.nextInt(maxIndex);
        mSwitcher.setText(textToShow[generatedIndex]);
        mSwitcher1.setText(textToShow1[generatedIndex]);
    }

    private ViewFactory mFactory = new ViewFactory() {

        @Override
        public View makeView() {

            // Create a new TextView
            TextView t = new TextView(MainActivity.this);
            t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
            t.setTextAppearance(MainActivity.this, android.R.style.TextAppearance_Large);
            return t;
        }
    };

}

2 个答案:

答案 0 :(得分:3)

如果您只想为文字制作动画,我建议您使用TextSwitcher

TextSwitcher可用于为屏幕上的标签设置动画,并且易于使用 您只需将文本设置为“视图”,即可使用setInAnimationsetOutAnimation

设置的动画设置动画文字

要安排文字更改,您可以使用TimerTaskHandler

使用Timer,您可以安排TimerTask在指定的延迟时重复

// ...    
// init view, init TextSwitcher in your onCreate
// ...

Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 0, 1000);

class MyTimerTask extends TimerTask {
    @Override public void run () {
        updateTextView(); // where you call setText(String) for TextSwitcher views
    }
}


以下是一些更详细的例子:
- TimerTask
- TextSwitcher

答案 1 :(得分:0)

有一个关于Android开发者网站上的CrossFading视图的教程:

http://developer.android.com/training/animation/crossfade.html

这是一个几乎完成的淡入淡出动画设置,你的textView使用这样的东西:

// ** ObjectAnimator Class To animate your first TextView
        ObjectAnimater  animationFadeIn = ObjectAnimator.ofFloat(textView, "alpha", 0f, 1f);
        animationFadeIn.setDuration(300);
        animationFadeIn.start();

并且淡出使用相同但是翻转来自浮动

// ** ObjectAnimator Class To animate your first TextView
        ObjectAnimater  animationFadeOut = ObjectAnimator.ofFloat(textView, "alpha", 1f, 0f);
        animationFadeOut.setDuration(300);
        animationFadeOut.start();

如果你想让它像你说的那样工作,可能想要考虑一个计数器,或者可能会淡化淡出的淡入淡出,这样你的视图就会显示和隐藏。

计数器逻辑可以如下:

 // This code will have to be called multiple times, once for each Time you want to Fade
 // Add a timer and start it 

 Timer timer1 = new Timer();


 // pass a different id here when initializing a new UpdateView() Object
 timer1.schedule(new UpdateView(0), 0, 5000);


// Inner Class to Use to run the Animations on your Items
public class UpdateView extends TimerTask
{
  int m_item = item;


  // This id is used to tell which view you want to animate FadeIn
  public UpdateView(int item)
  {
      this.m_item = item;
  }

   @Override
   public void run()
   {
       randomize();
   }

   public void randomize(int item)
   {
      Random random      = new Random();
      int maxIndex       = mTestArray.length;
      int generatedIndex = random.nextInt(maxIndex);


      // Switch on the TextView item type using an int
      switch(item)
      {
        // Want to Update an Animate TextView 
        case 0: 

            textView.setText(mTestArray[generatedIndex]);
            animateViewFadeIn(textView);
            animateViewFadeOut(textView1);

        break;
        // Want to Update an Animate TextView 1
        case 1: 
            textView1.setText(mTestArray1[generatedIndex]);
            animateViewFadeIn(textView1);
            animateViewFadeOut(textView);
        break;

      }

   }

   // Fade In
   public void animateViewFadeIn(TextView textView)
   {
        // Do animator Stuff here
        ObjectAnimator animation = ObjectAnimator.ofFloat(textView, "alpha",0f,1f);
        animation.setDuration(300);
        animation.start();

   }

   // Fade Out
   public void animateViewFadeOut(TextView textView)
   {
        // Do animator Stuff here
        ObjectAnimator animation = ObjectAnimator.ofFloat(textView, "alpha",1f,0f);
        animation.setDuration(300);
        animation.start();

   }
}