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

手機衛士實戰:自定義可獲焦點的跑馬燈 TextView

編輯:關於 Android 開發

打造始終獲焦的跑馬燈文字效果

本文將實現標題欄下方 TextView 的文字跑馬燈效果,讓一行文字水平循環滾動。先看效果:

一、直接用系統 TextView 實現

<!-- android:ellipsize="marquee" 設置跑馬燈效果 -->
<!-- 想讓文字出現跑馬燈效果,必須讓其獲取焦點 -->
<!-- android:marqueeRepeatLimit="marquee_forever" 一直滾動屬性 -->
<TextView
 android:text="這是一個跑馬燈,這是一個跑馬燈,這是一個跑馬燈,這是一個跑馬燈,這是一個跑馬燈,"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:ellipsize="marquee"
 android:focusable="true"
 android:focusableInTouchMode="true"
 android:marqueeRepeatLimit="marquee_forever"
 android:padding="5dp"
 android:textColor="#000"
 android:singleLine="true" />

如果多處都需要跑馬燈效果,每次都複製這一大段屬性顯得繁瑣。此處我們用自定義控件來實現,核心思路其實很簡單——重寫 TextView,讓它始終能夠獲取焦點即可。

二、新建 FocusTextView 自定義控件

先新建一個 view 包,專門存放自定義控件文件,並在其中創建 FocusTextView 類:

package com.wuyudong.mobilesafe.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 能夠獲取焦點的自定義 TextView
 */
public class FocusTextView extends TextView {
 // 用於通過 java 代碼創建控件
 public FocusTextView(Context context) {
 super(context);
 }
 // 由系統調用(帶屬性 + 上下文環境構造方法)
 public FocusTextView(Context context, AttributeSet attrs) {
 super(context, attrs);
 }
 // 由系統調用(帶屬性 + 上下文環境 + 布局樣式構造方法)
 public FocusTextView(Context context, AttributeSet attrs, int defStyle) {
 super(context, attrs, defStyle);
 }
 // 重寫獲取焦點的方法
 @Override
 public boolean isFocused() {
 return true;
 }
}

三、在布局中替換使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >
 <TextView style="@style/TitleStyle" android:text="功能列表" />
 <com.wuyudong.mobilesafe.view.FocusTextView
 android:text="這是一個跑馬燈,這是一個跑馬燈,這是一個跑馬燈,這是一個跑馬燈,這是一個跑馬燈,"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:ellipsize="marquee"
 android:marqueeRepeatLimit="marquee_forever"
 android:padding="5dp"
 android:textColor="#000"
 android:singleLine="true">
 </com.wuyudong.mobilesafe.view.FocusTextView>
</LinearLayout>

自定義控件編寫流程小結

1. 創建一個類繼承自 TextView(FocusTextView);
2. 重寫其各個構造方法;
3. 將獲焦方法 isFocused() 的返回值改為 true,讓控件始終能獲取焦點;
4. 使用時,將該類的全路徑名稱作為 XML 標籤,其餘屬性用法與普通 TextView 完全一致。

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