Android学习笔记(实现跑马灯效果的两种方式 )
一、使用TextView
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="跑马灯的文字要长,必须设置成单行显示。跑马灯的文字要长,必须设置成单行显示。跑马灯的文字要长。"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"/>
说明:
1>android:singleLine=”true” 设置为文字单行显示
2>android:ellipsize=”marquee” 设置跑马灯效果
3>android:focusable=”true” 设置获取焦点,没有焦点的TextView,即使设置了android:ellipsize=”marquee”也是无效的
4>android:focusableInTouchMode=”true” 设置屏幕被触摸时TextView获取焦点
二、自定义一个强制有焦点的控件
1.首先创建一个类继承自TextView
2.重写4个构造方法
3.重写isFocused()方法 ,强制返回true 使FocusedTextView默认就有焦点。
public class FocusedTextView extends TextView{
@Override
public boolean isFocused() {
// 注销掉 return super.isFocused();
return true;
}
public FocusedTextView(Context context) {
super(context);
}
public FocusedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FocusedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FocusedTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}
4.使用FocusedTextView来实现跑马灯
<你的包名.FocusedTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="跑马灯的文字要长,必须设置成单行显示。跑马灯的文字要长,必须设置成单行显示。跑马灯的文字要长。"
android:singleLine="true"
android:ellipsize="marquee"/>
这样只需要android:singleLine=”true” 和 android:ellipsize=”marquee” 这两句就够了