作者:Yogi
前言:此篇文章告訴你如何讓TextView的字體放大且能夠自滾動。
背景
TextView是listView上item的一個控件,要求如下:
1.當未被選中時,正常字體大小,若不能完全顯示,則自滾動
2.當被選中時,字體放大一定倍數,若不能完全顯示,則自滾動。
解決辦法
解決要求1
針對要求1,我們可以繼承TextView,定義一個超出顯示範圍則自滾動的控件,並在layout文件中使用這個控件,自定義控件代碼如下:
package com.yogi.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MarqueeTextView extends TextView {
public MarqueeTextView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
}
public MarqueeTextView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public MarqueeTextView(final Context context) {
super(context);
}
@Override
public final boolean isFocused() {
return true;
}
}
佈局文件代碼如下:
<com.yogi.view.MarqueeTextView
android:id="@+id/channel_num"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:textColor="@color/textColor_normal"
android:textSize="@dimen/channel_list_item_text_size"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
/>
解決要求2
針對要求2,開始我們採用了動畫的形式,在onItemSelected中調用如下代碼:
public void selected() {
if (!isZoomOut) {
mTvLcn.startAnimation(biggerAnim);
isZoomOut = !isZoomOut;
}
}
動畫代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:fillEnabled="true">
<scale
android:fromXScale="100%" android:toXScale="130%"
android:fromYScale="100%" android:toYScale="130%"
android:pivotX="0%" android:pivotY="50%"
android:duration="100"
/>
</set>
但是發現
1.正常字體大小時未超出顯示範圍,但字體放大後的文本已經超出顯示範圍了,可是並沒有自滾動
2.正常字體大小時,就超出顯示範圍的文本,在未被選中時,就會自滾動,當字體放大後,依然會自滾動,可是自滾動時,字體大小與正常大小一致,並沒有保持字體放大後的效果
所以這樣的解決方法是不行的。我們需要另想辦法。
可是爲何會出現上述情況呢?爲何自滾動時,被放大的字體會變成正常字體大小呢?爲何正常字體大小未超出顯示範圍時,即使放大後的文本已經超出顯示範圍了,卻依然沒有自滾動呢?
我的猜測:TextView是以什麼來衡量是否超出顯示範圍的?以設定死的textSize來計算並與顯示範圍進行比較來判斷的?
想到這個,我驗證了一下,的確如此。所以代碼改成了如下:
public void selected() {
if (!isZoomOut) {
mTvLcn.startAnimation(biggerAnim);
LogUtil.d(TAG, "selected mTvLcn.getTextSize()=" + mTvLcn.getTextSize());
mTvProgramName.setTextSize(BIG_TEXT_SIZE);
isZoomOut = !isZoomOut;
}
}
而且,通過在setTextSize前的打印,你會發現即使調用了放大的動畫,在界面表現上字體確實放大了,但是在代碼中textSize並沒有放大,而是正常大小,必須顯式地調用setTextSize,此textView的字體大小才真正改變,TextView就能夠自滾動。
總結
讓TextView自滾動,只要重寫isFocused函數並返回true即可。要讓放大後的文本自滾動,必須顯式地調用setTextSize。