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

Android 在 GridView 中實現 TextView 跑馬燈效果

編輯:關於 Android 程式設計

若要在 GridView 中的 TextView 實現跑馬燈(Marquee)效果,直覺上會先在 TextView 中加入以下屬性:

android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:gravity="center"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"

但你會發現這在 GridView 中並無效,而且會導致 GridView 無法點擊。問題的根源在於 TextView 的焦點狀態——只有當 View 處於 focus 狀態時跑馬燈才會啟動,而 GridView 中的 item 預設並不會取得焦點。

解決辦法是自定義一個 TextView,覆寫其 isFocused() 方法,強制回傳 true:

package com.shangc.mycar.custom;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 自定義 TextView,在 GridView 中實現跑馬燈效果。
 * 覆寫 View 裡面的 isFocused() 方法,預設情況下是不會有效果的,
 * 而且會導致 GridView 無法點擊。
 */
public class MyGridViewTextView extends TextView {
    public MyGridViewTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public MyGridViewTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public boolean isFocused() {
        return true;
    }
}

使用這個自定義的 TextView,並記得移除 android:focusable="true" 屬性,即可讓 GridView 中的文字正確呈現跑馬燈捲動效果,同時保持 GridView 的正常點擊。

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