Android中TextView滚动显示信息的效果

废话少说 , 先展示下效果图:
图一是只有一条信息时 , 不滚动展示 ;
图二是有多条信息时 , 滚动展示信息.

这里写图片描述 图一

这里写图片描述 图二

代码如下:

☆☆☆自定义控件的代码:

package com.eg.lyx.ctsscrolltextview;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

/**
 * Created by li_yx on 2017/5/17.
 */

public class CtsScrollTextView extends LinearLayout {

    private Context mContext;
    private TextView textViews[] = new TextView[3];

    private LinearLayout llayout;

    private String curText = null;

    /***
     * 每次动画执行时间
     */
    private int mAnimTime = 500;

    /**
     * 停留时间
     */
    private int mStillTime = 1500;

    /***
     * 轮播的string
     */
    private List<String> mTextList;

    /***
     * 当前轮播的索引
     */
    private int currentIndex = 1;

    /***
     * 动画模式
     */
    private int animMode = 0;// 默认向上 0--向上,1--向下

    public final static int ANIM_MODE_UP = 0;
    public final static int ANIM_MODE_DOWN = 1;

    private TranslateAnimation animationDown, animationUp;

    public CtsScrollTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initViews();
    }

    private void initViews() {
        llayout = new LinearLayout(mContext);
        llayout.setOrientation(LinearLayout.VERTICAL);
        this.addView(llayout);

        textViews[0] = addText();
        textViews[1] = addText();
        textViews[2] = addText();
    }

    /***
     * 当界面销毁时
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAutoScroll();// 防止内存泄漏的操作
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setViewsHeight();
    }

    /***
     * 重新设置VIEW的高度
     */
    private void setViewsHeight() {
        for (TextView tv : textViews) {
            LayoutParams lp = (LayoutParams) tv.getLayoutParams();
            lp.height = getHeight();
            lp.width = getWidth();
            tv.setLayoutParams(lp);
            tv.setTextColor(getResources().getColor(R.color.white));
            tv.setMaxLines(2);
            tv.setEllipsize(TextUtils.TruncateAt.END);
        }

        LayoutParams lp2 = (LayoutParams) llayout.getLayoutParams();
        lp2.height = getHeight() * (llayout.getChildCount());
        lp2.setMargins(0, -getHeight(), 0, 0);// 使向上偏移一定的高度,用padding,scrollTo都分有问题
        llayout.setLayoutParams(lp2);
    }


    public void setTextList(List<String> mTextList) {
        this.mTextList = mTextList;
    }


    private TextView addText() {
        TextView tv = new TextView(mContext);
        tv.setGravity(Gravity.CENTER_VERTICAL);
        llayout.addView(tv);
        return tv;
    }

    /***
     * 设置初始的字
     */
    public void setText(String curText) {
        this.curText = curText;
        textViews[1].setText(curText);
    }

    /***
     * 开始自动滚动
     */
    public void startAutoScroll() {
        if (mTextList == null || mTextList.size() == 0 || mTextList.size() == 1) {
            return;
        }
        // 先停止动画
        stopAutoScroll();
        this.postDelayed(runnable, mStillTime);// 可用runnable来代替hander或者 timer
    }

    /***
     * 停止自动滚动
     */
    public void stopAutoScroll() {
        this.removeCallbacks(runnable);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            currentIndex = (currentIndex) % mTextList.size();
            switch (animMode) {
                case ANIM_MODE_UP:
                    setTextUpAnim(mTextList.get(currentIndex));
                    break;
                case ANIM_MODE_DOWN:
                    setTextDownAnim(mTextList.get(currentIndex));
                    break;
            }
            currentIndex++;
            CtsScrollTextView.this.postDelayed(runnable, mStillTime + mAnimTime);

        }
    };


    public void setTextUpAnim(String text) {
        this.curText = text;
        textViews[2].setText(text);
        up();// 向上的动画
    }


    public void setTextDownAnim(String text) {
        this.curText = text;
        textViews[0].setText(text);
        down();// 向上的动画
    }


    /***
     * 向上动画
     */
    private void up() {
        llayout.clearAnimation();
        if (animationUp == null)
            animationUp = new TranslateAnimation(0, 0, 0, -getHeight());
        animationUp.setDuration(mAnimTime);
        llayout.startAnimation(animationUp);
        animationUp.setAnimationListener(listener);
    }

    /***
     * 向下动画
     */
    public void down() {
        llayout.clearAnimation();
        if (animationDown == null)
            animationDown = new TranslateAnimation(0, 0, 0, getHeight());
        animationDown.setDuration(mAnimTime);
        llayout.startAnimation(animationDown);
        animationDown.setAnimationListener(listener);
    }

    /***
     * 动画监听,动画完成后,动画恢复,设置文本
     */
    private Animation.AnimationListener listener = new Animation.AnimationListener() {

        @Override
        public void onAnimationStart(Animation arg0) {
        }

        @Override
        public void onAnimationRepeat(Animation arg0) {
        }

        @Override
        public void onAnimationEnd(Animation arg0) {
            setText(curText);
        }
    };


    //-----------------------------------以下是textView要用到一些基本方法-----------------------------------
    public void setGravity(int graty) {
        for (TextView tv : textViews) {
            tv.setGravity(graty);
        }
    }

    public void setTextSize(int dpSize) {
        for (TextView tv : textViews) {
            tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, dpSize);
        }
    }

    public void setTextColor(int color) {
        for (TextView tv : textViews) {
            tv.setTextColor(color);
        }
    }

    public void setAnimTime(int mAnimTime) {
        this.mAnimTime = mAnimTime;
    }

    public void setStillTime(int mStillTime) {
        this.mStillTime = mStillTime;
    }

    public void setCurrentIndex(int currentIndex) {
        this.currentIndex = currentIndex;
    }

    public void setDuring(int during) {
        this.mAnimTime = during;
    }

    public void setAnimMode(int animMode) {
        this.animMode = animMode;
    }
}

☆☆☆布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ctsFligthCardStatus"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:layout_marginTop="20dp"
    android:background="#FF17BC26"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/ctsFlightCardStatusNameTv"
        android:layout_width="wrap_content"
        android:layout_height="33dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        android:gravity="center_vertical"
        android:text="三体"
        android:textColor="#FFFFFFFF"
        android:textSize="22sp"/>

    <View
        android:layout_width="0.5dp"
        android:layout_height="30dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="15dp"
        android:background="#FFFFFFFF"/>

    <com.eg.lyx.ctsscrolltextview.CtsScrollTextView
        android:id="@+id/ctv"
        android:layout_width="0dp"
        android:layout_height="33dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"/>

</LinearLayout>

☆☆☆Activity代码:

package com.eg.lyx.ctsscrolltextview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;

import java.util.ArrayList;

import static android.R.id.list;

public class MainActivity extends AppCompatActivity {

    private CtsScrollTextView ctv;

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

        ctv = (CtsScrollTextView) findViewById(R.id.ctv);

        ArrayList<String> list = new ArrayList<>();
        list.add(getResources().getString(R.string.text1));
        list.add(getResources().getString(R.string.text2));
        list.add(getResources().getString(R.string.text3));
        list.add("第四条信息");
        list.add("第五条信息");


        if (list.size() != 0) {
            ctv.setText(list.get(0));
        }
        ctv.setTextList(list);
        ctv.startAutoScroll();
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: 可以使用TextView的setMovementMethod()方法来实现滚动效果。具体步骤如下: 1. 在布局文件添加一个TextView控件。 2. 在代码获取TextView控件的实例。 3. 调用setMovementMethod()方法,将其参数设置为ScrollingMovementMethod的实例。 示例代码如下: XML布局文件: <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_scroll" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="这是一段需要滚动的文本"/> </ScrollView> Java代码: TextView tvScroll = findViewById(R.id.tv_scroll); tvScroll.setMovementMethod(new ScrollingMovementMethod()); 这样就可以实现TextView滚动效果了。 ### 回答2: Android Studio是一款广受欢迎的开发工具,其TextView是最常用的控件之一。在某些场景下,我们需要让TextView的内容进行滚动显示,这时就需要使用一些特定的代码来实现这个功能。 首先,在XML布局文件定义一个TextView控件,如下所示: ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这是一段需要滚动的文本" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:focusable="true" android:focusableInTouchMode="true" /> ``` 上述代码,我们使用了以下属性来定义TextView滚动效果: - android:singleLine="true":将TextView限制为一行; - android:ellipsize="marquee":使用“跑马灯”效果; - android:marqueeRepeatLimit="marquee_forever":设置“跑马灯”无限循环; - android:focusable="true":让TextView获取焦点; - android:focusableInTouchMode="true":在触摸模式下让TextView获取焦点。 接下来,在Java文件添加以下代码: ``` TextView textView = findViewById(R.id.textView); textView.setSelected(true); ``` 这里我们调用了TextView的setSelected方法,将TextView的选状态设置为true,这是让“跑马灯”效果生效的必要条件。 值得注意的是,如果TextView的布局包含了ScrollView或ListView等可滚动控件,那么我们需要通过设置焦点来禁止TextView滚动,否则可能会与可滚动控件产生冲突。 综上所述,通过设置特定属性和调用特定方法,我们就可以实现TextView滚动效果了。同时,需要注意防止与其他控件产生冲突,保证滚动效果正常运行。 ### 回答3: Android StudioTextView控件默认情况下是不支持滚动的,但在开发有时我们需要显示超长文本,就需要使用TextView滚动功能。 一种简单的实现方式是将TextView嵌套在一个ScrollView,但这种方式的效率不高,会出现卡顿和占用过多内存等问题。因此,我们需要使用更高效的方法实现TextView滚动。 在AndroidTextView滚动可以通过代码实现。以下是实现TextView滚动的一些常用方法: 1. 使用Scroller类 Scroller类可以实现平滑的滚动效果。我们可以使用Scroller类的startScroll方法和computeScroll方法实现文本滚动。代码如下: ```java TextView textView = findViewById(R.id.text_view); Scroller scroller = new Scroller(this); scroller.startScroll(0, 0, 0, -textView.getLineHeight() * textView.getLineCount(), 1000); textView.invalidate(); ``` startScroll方法,第一个参数和第二个参数是文本滚动的起点坐标,第三个参数和第四个参数是文本滚动的偏移量,第五个参数是滚动的时间,单位是毫秒。 computeScroll方法,我们需要重写文本滚动的逻辑,代码如下: ```java @Override public void computeScroll() { if (scroller.computeScrollOffset()) { textView.scrollTo(scroller.getCurrX(), scroller.getCurrY()); textView.postInvalidate(); } } ``` 2. 使用属性动画 属性动画可以实现平滑的滚动效果。我们可以使用属性动画的translationY属性实现文本滚动。代码如下: ```java TextView textView = findViewById(R.id.text_view); ObjectAnimator animator = ObjectAnimator.ofFloat(textView, "translationY", 0, -textView.getLineHeight() * textView.getLineCount()); animator.setDuration(1000); animator.start(); ``` 3. 使用ValueAnimator类 ValueAnimator类可以实现平滑的滚动效果。我们可以使用ValueAnimator类的setFloatValues方法和setEvaluator方法实现文本滚动。代码如下: ```java TextView textView = findViewById(R.id.text_view); ValueAnimator animator = ValueAnimator.ofFloat(0, -textView.getLineHeight() * textView.getLineCount()); animator.setDuration(1000); animator.setEvaluator(new TypeEvaluator<Float>() { @Override public Float evaluate(float fraction, Float startValue, Float endValue) { return startValue + fraction * (endValue - startValue); } }); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { textView.setTranslationY((Float) animator.getAnimatedValue()); } }); animator.start(); ``` 以上是TextView滚动的一些常用方法,我们可以根据需要选择合适的方法实现滚动效果,提高应用的用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值