編輯:關於 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 軟體編程有所幫助。
Android Studio 教程(一):下載安裝與創建 HelloWorld 項目
相信大家对 Android Studio 已經不陌生了。它是 Google 於 2013 I/O 大會針對 Android 開發推出的全新 IDE,目前越來越多開源項目都
Android 源碼解析(十四):Activity 啟動流程
Activity 是 Android 應用中最核心的組件之一。理解 Activity 的啟動流程,不僅能幫助我們更好地掌握 Android 系統的工作機制,也能讓我們在面
實例講解 Android 自定義組合控件的方法
自定義 View 大致可分為四類:繼承 View、組合 View、自繪 View(用 Paint 和 Canvas)、自定義 ViewGroup(Widget)。本文聚焦
Android 實習札記(6):ViewPager 從入門到自定義 Tab
上一節我們用 Fragment 拼了一個簡單的底部導航欄,結尾提到要結合 ViewPager 做引導界面。說到 ViewPager,很多人應該都用過,但如果只會複製粘貼、