Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android TextView 實現跑馬燈效果的方法

編輯:關於 Android 程式設計

本文分享一個既簡單又實用的控件——帶跑馬燈效果的 TextView。當要顯示的文字太長、又不想換行時,用它來展示就再合適不過了:既能完整顯示文字,滾動的效果也頗為加分,而實現起來更是輕鬆。先來看看效果:

其實 TextView 本身就自帶跑馬燈功能,只要把 ellipsize 屬性設為 marquee 即可。但前提是該 TextView 必須處於「被選中」狀態才會生效。為此,我們可以自定義一個控件,重寫 isFocused 方法,讓設定了 marquee 屬性的 TextView 永遠保持選中狀態:

 public class MarqueeTextView extends TextView { public MarqueeTextView(Context con) { super(con); } public MarqueeTextView(Context context, AttributeSet attrs) { super(context, attrs); } public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean isFocused() { // TODO Auto-generated method stub if(getEditableText().equals(TruncateAt.MARQUEE)){ return true; } return super.isFocused(); } } 

重寫 isFocused 並加入判斷後,只有設定了 marquee 屬性的才會保持選中狀態,其餘行為與普通 TextView 無異。接著就能在布局中直接使用:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <FrameLayout android:id="@+id/titlebar_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#39ac69" > <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:background="#ffffff" android:gravity="center_vertical" android:orientation="horizontal" > <ImageView android:id="@+id/home_location_iv" android:layout_width="25dp" android:layout_height="27dp" android:layout_marginLeft="10dp" android:scaleType="fitXY" android:src="@drawable/icon_place" /> <com.lxj.marqueetextview.MarqueeTextView android:id="@+id/home_location_tv" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_weight="1" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:gravity="center" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:singleLine="true" android:text="正在定位..." android:textColor="#39ac69" android:textSize="18sp" /> <ImageView android:id="@+id/home_search_iv" android:layout_width="25dp" android:layout_height="27dp" android:layout_marginRight="10dp" android:scaleType="fitXY" android:src="@drawable/icon_place" /> </LinearLayout> </FrameLayout> </LinearLayout> 

使用時要特別注意兩點:ellipsize 屬性要設為 "marquee",且 singleLine 要設為 true。做到這兩點,TextView 的跑馬燈效果就大功告成了。希望本文對大家學習 Android 軟體編程有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved