【问题标题】:How to add CrossFade effect in Textview, Android如何在 Android 的 Textview 中添加 CrossFade 效果
【发布时间】:2014-02-25 20:09:07
【问题描述】:

以下代码从两个数组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]);  
        }
    }

示例.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>

行星阵列

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

}

【问题讨论】:

    标签: android string animation random


    【解决方案1】:

    如果您只想为文本设置动画,我建议您使用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

    【讨论】:

    • 如何在没有点击功能的情况下使用 TextSwitcher?我不想使用任何类型的按钮。我想使用延迟,而且我会使用两组文本吗?我能随机化输出吗?
    • 我遇到了一个错误,你能看看我做错了什么吗?
    • 您在每次更新时将 ViewFactory 设置为 TextSwitchers,需要在主线程上执行 run 方法等。这是您的类,已修改为显示动画 pastebin.com/VDGXPYTT
    【解决方案2】:

    在 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();
    
       }
    }
    

    【讨论】:

    • 感谢您的快速响应,但要使用此代码,我是否需要创建一个名为 updateview 的新类?我有点困惑,对不起新的安卓开发者。
    • 您可以将其用作 Activity 类中的类。这样您就不必将所有数组和 textViews 传递给构造函数。
    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 2012-02-21
    • 2011-03-28
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2012-04-01
    • 2019-09-29
    相关资源
    最近更新 更多