Android TextView跑馬燈效果

openkk 12年前發布 | 96K 次閱讀 Android Android開發 移動開發

所謂跑馬燈效果就是當文字超過控件所能容納的空間時,在控件內滾動的效果。

走馬燈的效果主要是通過android:singleLine,android:ellipsize,android:marqueeRepeatLimit,android:focusable屬性來配置的。

android:singleLine="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:focusable="true"
android:marqueeRepeatLimit="marquee_forever"

  • android:singleLine=true 表示使用單行文字,多行文字也就無所謂使用Marquee效果了。
  • android:marqueeRepeatLimit,設置走馬燈滾動的次數。
  • android:ellipsize,設置了文字過長時如何切斷文字,可以有none, start,middle, end, 如果使用走馬燈效果則設為marquee.
  • android:focusable,Android的缺省行為是在控件獲得Focus時才會顯示走馬燈效果

顯示跑馬燈效果的前提條件就是你的文本內容要比顯示文本的外部組件長,即外部組件無法完整的顯示內部的文本內容。

因此要實現跑馬燈效果有兩種設置方式:

1、layout_width=”"設置為成比文本內容短的固定值,最好不要寫成wrap_content或者fill_parent。

2、如果layout_width=”"設置wrap_content或者fill_parent,那么可以增加上 android:paddingLeft="15dip",android:paddingRight="15dip"使兩端的距離加大而無法全部顯示文本內容,但是這有一個缺陷就是在手機的屏幕變大時,距離沒有變大,外部組件又可以正常顯示內部文本,于是又無法顯示跑馬燈效果,因此建議第一種設置為佳。
      

另外還可以設置滾動的次數android:marqueeRepeatLimit=”";android:marqueeRepeatLimit=”marquee_forever”表示一直滾動。

當有些情況下需要是文字一直滾動以引起用戶注意,這是可以使用派生TextView,重載onFocusChanged,onWindowFocusChanged,isFocused 這三個方法。

修改一下本例,添加一個ScrollAlwaysTextView類:

public class ScrollAlwaysTextView extends TextView {

 public ScrollAlwaysTextView(Context context) {
 this(context, null);
 }

 public ScrollAlwaysTextView(Context context, AttributeSet attrs) {
 this(context, attrs, android.R.attr.textViewStyle);
 }

 public ScrollAlwaysTextView(Context context, AttributeSet attrs,
 int defStyle) {
 super(context, attrs, defStyle);
 }

 @Override
 protected void onFocusChanged(boolean focused, int direction,
 Rect previouslyFocusedRect) {
 if (focused)
 super.onFocusChanged(focused, direction, previouslyFocusedRect);
 }

 @Override
 public void onWindowFocusChanged(boolean focused) {
 if (focused)
 super.onWindowFocusChanged(focused);
 }

 @Override
 public boolean isFocused() {
 return true;
 }
}


 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!