android实现跑马灯的效果第一种是页面只有一个TextView或从上至下,从左至右的第一个TextView需要跑马灯效果,实现方式为:
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:text="@string/text" android:textSize="26sp"/>
第二种方式是有多个TextView需要同时实现跑马灯效果,实现方式为自定义一个类,继承TextView,并且实现它的三个构造方法,同时实现isFocused方法,将它的返回值设置为true即可完成多个TextView跑马灯的效果,具体实现方式如下:
public class MarqueeText extends TextView { public MarqueeText(Context context) { super(context); } public MarqueeText(Context context, AttributeSet attrs) { super(context, attrs); } public MarqueeText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /* isFocused方法一定要重写 */ @Override public boolean isFocused() { return true; } }
在xml布局文件中,通过自定义的类实现TextView:
<com.example.bjtest1.MarqueeText android:id="@+id/tv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:text="@string/text" android:textSize="26sp"/> <com.example.bjtest1.MarqueeText android:id="@+id/tv2" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:layout_marginTop="10dp" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:text="@string/text" android:textSize="26sp"/>两种方式已全部分享完毕!!!