最近買了本《Android Studio開發實戰 從零基礎到APP上線》的書,裏面的第一個實例就是跑馬燈效果,按照書上的代碼寫好了,可是執行起來卻沒有效果。
下面先把代碼貼出來。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是一個跑馬燈效果的文本試圖,裏面的文字太長了,具體多少我也不知道,此處略去十萬字!!!"
android:textColor="#00ff00"
android:singleLine="true"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true" />
</LinearLayout>
直接執行程序,發現一點反應都沒有。教程中的例子是用下面這樣的方式來實現的
if (v.getId() == R.id.tv_hello) {
cpaust = !cpaust;
if (cpaust){
tv_hello.setFocusableInTouchMode(true);
tv_hello.setFocusable(true);
} else {
tv_hello.setFocusable(false);
tv_hello.setFocusableInTouchMode(false);
}
}
但是,這種方式來實現就失去了原有的意義了,試想一下,跑馬燈肯定是頁面一打開就開始滾動的,誰會設計成要去點擊才能運行呢。
所以就找另一種方案解決,網上找了很多文章,都說是那幾個屬性設置一下就可以,結果都不行。最後找到一個,就是在activity中加一行
tv_hello.setSelected(true);
就這麼一行,效果馬上就有了。
總結一下:
跑馬燈的幾個比較重要的屬性:
android:singleLine="true" //必須是單行顯示
android:ellipsize="marquee" //顯示爲跑馬燈效果
android:marqueeRepeatLimit="marquee_forever" //設置滾動方式爲永久滾動
android:focusable="true" //設置焦點
android:focusableInTouchMode="true" //設置觸屏焦點
以上幾個屬性必須這樣設置才行。還有一點,文字的長度必須要大於屏幕的長度才能滾動的起來。