今天发现AS工作空间躺着一个滚动文本的demo,记不起来什么时候写的,瞄一眼,确实很简单,决定放到博客中来。
直接看代码(代码中注释就能帮助你理解):
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
注意:最后两个属性很重要。
是的,其实TextView直接加上这些属性也可以实现文本的滚动,但是如果你要是多个TextView就不行了。那我们怎么做呢?我们让多个TextView都获取焦点,可以自定义下,看代码:
/**
* Created by Qly on 2016/4/20.
*/
public class MarqueeTextview extends TextView {
public MarqueeTextview(Context context) {
super(context);
}
public MarqueeTextview(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MarqueeTextview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 重写获取焦点方法,使其返回true
* @return
*/
@Override
public boolean isFocused() {
return true;
}
}
说真的这是我见过最简单的自定义View,好吧!我承认这样很low。
看布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.testdemo.MainActivity">
<com.example.testdemo.view.MarqueeTextview
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:text="这是一个自定义的带有跑马灯效果的TextView这是一个自定义的带有跑马灯效果的TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
<com.example.testdemo.view.MarqueeTextview
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:text="这是一个自定义的带有跑马灯效果的TextView这是一个自定义的带有跑马灯效果的TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
<com.example.testdemo.view.MarqueeTextview
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:text="这是一个自定义的带有跑马灯效果的TextView这是一个自定义的带有跑马灯效果的TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
<com.example.testdemo.view.MarqueeTextview
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:text="这是一个自定义的带有跑马灯效果的TextView这是一个自定义的带有跑马灯效果的TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
</LinearLayout>
效果就是酱紫: