當TextView顯示為單行并且文字過長的時候就需要跑馬燈效果。
最簡單的方法,我們可以在TextView中設定幾個屬性就可以實作跑馬燈效果,代碼如下:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:text="@string/hello_world"
android:focusable="true"/>
但是如果有多個TextView都需要這種效果就不能滿足了,我們需要自定義TextView
public class MyTextView extends TextView{
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
public boolean isFocused() {
//這裡傳回true,讓textView擷取焦點
return true;
}
}
在布局中引用我們自己定義的TextView
<com.example.mtextview.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:text="@string/hello_world"
android:focusable="true"/>
<com.example.mtextview.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:text="@string/hello_world"
android:focusable="true"/>