本节的内容学习自慕课网,记录下来以便复习和查阅!
当布局文件比较单一,比如只有一个需要实现跑马灯的TextView时,可以直接通过设置TextView的属性来实现效果;
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_margin="10dp"
android:text="@string/hello_world" />
android:ellipsize="marquee"属性设置使得当文字超过TextView宽度是实现文字滚动,但是又必须在TextView获取到焦点才能实现文字滚动效果,所以还需设置属性:
android:focusable="true" 和 android:focusableInTouchMode="true"
当布局文件比较复杂的时候,比如有两个TextView需要实现跑马灯效果;这个时候通过设置TextView的属性会发现只有第一个TextView实现了跑马灯效果,因为焦点一直在第一个TextView上,所以第二个TextView没有获取到焦点也就没有实现跑马灯的效果;
解决的方法是自定义一个类继承TextView;然后重写其中的isFocused();如:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
@ExportedProperty(category = "focus")
public boolean isFocused() {
return true;
}
}
<com.example.mooc.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_margin="10dp"
android:text="@string/hello_world" />
<com.example.mooc.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_margin="10dp"
android:text="@string/hello_world" />
将该方法的返回值直接写成true,这样在布局文件中创建的所有MyTextView则都能够获取到焦点了;也就能够实现两个TextView的跑马灯效果了;
例外,android:marqueeRepeatLimit属性可以设置跑马灯的循环次数,如:android:marqueeRepeatLimit="-1"表示无限循环次数,android:marqueeRepeatLimit="1" 则表示支循环播放一次;