Android中TextView文字過長滾動顯示實現
阿新 • • 發佈:2019-01-09
專案中在使用TextView時,總會有因要顯示的內容過多而需要我們進行處理的問題。我們第一時間想到的是TextView的android:ellipsize屬性, 比如 android:ellipsize="end",效果是在文字的尾部打三個小點。 但是這個屬性要配合android:singLine="true"使用。通常來說,要實現尾端三個點的省略號形式是比較容易的。 如果要求文字全部顯示,但是為了儲存UI介面美觀,有限大小的TextView中如何顯示全部的超長文字呢,我們就想到了讓文字滾動顯示。 大家也想到了通過 android:ellipsize="marquee"來實現,不過我在專案中使用這個也沒有實現效果。 配合了android:singLine="true"也一樣不能實現文字滾動顯示。網上有很多解決方案,幾乎都是說到焦點問題。 比如有人建議在佈局檔案中的TextView新增 android:focusable="true",不過有時也是沒有效果的。 我的處理方法是,複寫TextView,只要簡單地改一個程式碼即可:
public class MarqueTextView extends TextView {
public MarqueTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MarqueTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MarqueTextView (Context context) {
super(context);
}
@Override
public boolean isFocused() {
//就是把這裡返回true即可
return true;
}
}
然後把複寫的TextView當成控制元件寫在佈局檔案中,新增:
android:marqueeRepeatLimit="marquee_forever"
android:ellipsize="marquee"
android:singleLine="true"
等屬性,當然不要忘記寫width,height等必備屬性哦。
最後在使用該TextView的時候,還要新增一句:
MarqueTextView tv=(MarqueTextView)findViewById(R.id.my_text_view);
tv.setSelected(true);
滾動效果就有了。