如何为textview(非常长的文本)设置动画水平自动滚动

时间:2013-09-16 11:30:17

标签: android textview

我对Marquee不感兴趣,因为在Marquee中你无法控制选框的速度。 我试图为textview设置动画,但是Parent视图会剪切最后的文本,即使包含textviews的所有父布局和视图组都设置了两个标志clipchildren = false,clipToPadding = false。

我错过了什么或是否有更好的解决方法?

xml看起来像

<TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="66dp"
        android:maxLines="1"
        android:singleLine="true"
        android:textColor="#585858"
        android:textSize="32sp" >
    </TextView>

和代码段看起来像

TextView textView2 = (TextView)findViewById( R.id.textview1 );    
textView2.startAnimation((Animation)AnimationUtils.loadAnimation(this, R.anim.translate));

11 个答案:

答案 0 :(得分:5)

我认为你可以使用翻译动画。像这样的东西

<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="5000"
    android:fromXDelta="100"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="infinite"
    android:repeatMode="restart"
    android:toXDelta="-100" />

并添加到您的textview中

textview.startAnimation((Animation)AnimationUtils.loadAnimation(Context,R.anim.scroll_animation));

希望它可以帮到你。

答案 1 :(得分:4)

只需将其添加到您的textview

即可
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:textSize="30dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:text="Your_Text" />

答案 2 :(得分:3)

这是我的解决方案

为了使textview中的长文本不被父视图或屏幕剪切,我做了两件事。

首先,将textview放在scroolview中,如下面的代码

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:layout_centerHorizontal="true">
    <TextView
        android:id="@+id/marquee_text"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:maxLines="1"
        android:textColor="@android:color/black"
        android:textSize="30sp"/>
</ScrollView>

然后,我测量文本大小,然后通过执行此操作来优化textview参数。

    marqueeText.setText("my long text");
    Paint textPaint = marqueeText.getPaint();
    String text = marqueeText.getText().toString();//get text
    int width = Math.round(textPaint.measureText(text));//measure the text size
    ViewGroup.LayoutParams params =  marqueeText.getLayoutParams();
    params.width = width;
    marqueeText.setLayoutParams(params); //refine

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getRealMetrics(displaymetrics);
    int screenWidth = displaymetrics.widthPixels;

    //this is optional. do not scroll if text is shorter than screen width
    //remove this won't effect the scroll
    if (width <= screenWidth) {
        //All text can fit in screen.
        return;
    }
    //set the animation
    TranslateAnimation slide = new TranslateAnimation(0, -width, 0, 0);
    slide.setDuration(20000);
    slide.setRepeatCount(Animation.INFINITE);
    slide.setRepeatMode(Animation.RESTART);
    slide.setInterpolator(new LinearInterpolator());
    marqueeText.startAnimation(slide);

我希望这个花了我半天研究的解决方案可以帮助那些可能遇到像我这样的问题的人。

答案 3 :(得分:1)

可以尝试一下。这是使用TranslateAnimation创建自动滚动文本(水平滚动,从右到左)的解决方案(在Android 8上测试)

类:AnimationAutoTextScroller.java

/**
 * A Class for automatically scrolling text horizontally from Right to Left 
 * using TranslateAnimation so that the scrolling speed can be controlled -Suresh Kodoor
 */

public class AnimationAutoTextScroller {

    Animation animator;
    TextView  scrollingTextView;
    int       duration = 50000;  // default value

    public AnimationAutoTextScroller(TextView tv, float screenwidth) {

        this.scrollingTextView = tv;
        this.animator = new TranslateAnimation(
                Animation.ABSOLUTE, screenwidth,
                Animation.RELATIVE_TO_SELF, -1f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f
        );
        this.animator.setInterpolator(new LinearInterpolator());
        this.animator.setDuration(this.duration);
        this.animator.setFillAfter(true);
        this.animator.setRepeatMode(Animation.RESTART);
        this.animator.setRepeatCount(Animation.INFINITE);

        // setAnimationListener();
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public void setScrollingText(String text) {
        this.scrollingTextView.setText(text);
    }

    public void start() {
        this.scrollingTextView.setSelected(true);
        this.scrollingTextView.startAnimation(this.animator);
    }

    public void setAnimationListener() {

        animator.setAnimationListener(new Animation.AnimationListener() {
            public void onAnimationStart(Animation animation) {
            }
            public void onAnimationEnd(Animation animation) {
                // This callback function can be used to perform any task at the end of the Animation
            }
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }
}

布局XML :(将TextView保留在Horizo​​ntalScrollView下)

 <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none"
        app:layout_constraintBottom_toTopOf="@+id/hguide3"
        app:layout_constraintEnd_toStartOf="@+id/vguide2"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/vguide1"
        app:layout_constraintTop_toBottomOf="@+id/hguide2">

    <TextView
        android:id="@+id/translateanimatortextviewscroller"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        android:text=""
        android:singleLine="true"
        android:focusable="true"
        android:scrollHorizontally="true"
        android:background="#000000ff"
        android:textColor="#ff0000"
        android:textSize="55dp"
        android:textStyle="bold"
        android:typeface="sans" />

      </HorizontalScrollView>

活动:

TextView scrollertextview = findViewById(R.id.translateanimatortextviewscroller);
textscroller = new AnimationAutoTextScroller(scrollertextview, screenwidth);
textscroller.setScrollingText(scrollertext);
textscroller.setDuration(60000);
textscroller.start();

答案 4 :(得分:1)

添加此动画文件:

<translate
    android:duration="7000"
    android:fromYDelta="0%p"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:repeatCount="10"
    android:repeatMode="restart"
    android:toYDelta="-100%p" />

/*Put your text view inside scroll*/
        <ScrollView
            android:layout_width="@dimen/dp_size_220"
            android:layout_height="@dimen/dp_size_16"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toRightOf="@+id/iv_myra_notification"
            app:layout_constraintRight_toLeftOf="@+id/iv_one_way"
            app:layout_constraintTop_toTopOf="parent">
            <TextView
                android:id="@+id/marquee_text"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="left"
                android:text="@{itemData.notification.message}"
                android:textColor="@android:color/black"
                android:textSize="12sp"
                tools:text="bfnfkjnvlen jknjkgnojeng"/>
        </ScrollView>

答案 5 :(得分:0)

这对我有用。 将您的textview放在滚动视图中,然后在scrollview的子项上执行 TranslateAnimation ,我的情况是LinearLayout。 我实际上是在这个线性布局中动态添加多个视图。

<ScrollView android:id="@+id/textScrollView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/textLayout"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </LinearLayout>
</ScrollView>

TranslateAnimation slide = new TranslateAnimation(0, 0, height, -textLayout.getHeight());
    slide.setDuration(movementSpeed);
    slide.setRepeatCount(-1);
    slide.setRepeatMode(Animation.RESTART);
    slide.setInterpolator(new LinearInterpolator());

textLayout.startAnimation(slide);

height --> The point start scrolling up (in my case device height (device bottom))
movementSpeed --> scrolling speed

答案 6 :(得分:0)

我百分百肯定这肯定会解决大量观众的问题。

问:自动滚动单行长文本消息(使用hard_coding或使用string.xml)水平&amp;以合理的速度无限地使用选框(至少尝试一次)。没有clliping

第1步: 在activity_main.xml文件中:

<TextView
    android:text="either hard coding or from string.xml"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView2"  
    android:background="@color/colorPrimary"
    android:textSize="18sp"
    android:marqueeRepeatLimit="marquee_forever"
    android:textColor="@android:color/background_light" />

第2步:在main_activity java文件中 公共类MainActivity扩展了AppCompatActivity {

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

    TextView textView = (TextView) findViewById(R.id.textView2);
    textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
    textView.setSelected(true);
    textView.setSingleLine(true);
    textView.setText("Oxfam says 8 men as rich as half the world. | Govt may set threshold for probe into deposits. | At least 32 dead after Turkish plane hits village.");}}

//如果他已经输入了长输入

,则可以删除最后一行

答案 7 :(得分:0)

使用@rajath answer

ellipsize 选框选项使用这种简单方法
<TextView
    android:text="Single-line text view that scrolls automatically if the text is too long to fit in the widget" 
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit ="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true" 
    android:scrollHorizontally="true"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/>

答案 8 :(得分:0)

它真令人沮丧,... 但是答案很简单, 使用Edittext代替TextView,然后将其包装在horizo​​ntalscrollview中 同时,setfocusable:false

   <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:scrollbars="none">

        <EditText
            android:id="@+id/post_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            android:focusable="false"
            android:outlineAmbientShadowColor="@color/colorPrimaryDark"
            android:shadowColor="#000000"
            android:shadowDx="1.5"
            android:shadowDy="1.3"
            android:shadowRadius="1.6"
            android:singleLine="true"
            android:textAlignment="center"
            android:textColor="@color/colorPrimary"
            android:textSize="20dp" />
    </HorizontalScrollView>

感谢Hein,添加动画代码

final EditText textView =  view.findViewById(R.id.post_message);
        textView.startAnimation((Animation) AnimationUtils.loadAnimation(context,R.anim.horizontal_animation));
        String message="LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLong Text.";
        textView.setText(message);

答案 9 :(得分:-1)

试试这段代码,它会帮助你摆脱Shri n HERO

<?xml version="1.0" encoding="utf-8"?>
<translate>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="5000"
    android:fromXDelta="1500"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="infinite"
    android:repeatMode="restart"
    android:toXDelta="-1250" />

</translate>

答案 10 :(得分:-1)

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate{

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> (Bool,Bool) {
        //Override point for customization after application launch.
       // return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
        var configureError: NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")

        GIDSignIn.sharedInstance().delegate = self

        return (true,FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions))
    }

    //func application(application: UIApplication,
    //    didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> (Bool,Bool) {
            // Initialize sign-in

    // }


      func application(application: UIApplication,
        openURL url: NSURL,
        sourceApplication: String?,
        annotation: AnyObject) -> (Bool,Bool) {

            return (FBSDKApplicationDelegate.sharedInstance().application(
                application,
                openURL: url,
                sourceApplication: sourceApplication,
                annotation: annotation), GIDSignIn.sharedInstance().handleURL(url,
                    sourceApplication: sourceApplication,
                    annotation: annotation))
    }

    func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
        withError error: NSError!) {
            if (error == nil) {
                // Perform any operations on signed in user here.
                let userId = user.userID                  // For client-side use only!
                let idToken = user.authentication.idToken // Safe to send to the server
                let name = user.profile.name
                let email = user.profile.email                // ...
            } else {
                print("\(error.localizedDescription)")
            }
    }
    func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
        withError error: NSError!) {
            // Perform any operations when the user disconnects from app here.
            // ...
    }
}