大家好,在我們通常的android project中,通常需要用到textview這一個布局文件,並且對於這一個顯示布局所需要的文本文字內容。
下面我們就來介紹一種方法來實現在android中用跑馬燈的效果來將一行內放不下的text文本表示出來。
首先,我們需要在布局文件中新建一個textview,對他如不進行任何操作將有如下顯示:
在demo中的顯示為:
感覺有點low,對此textview布局中加入如下布置,就可以實現跑馬燈的效果:
其中的:singleLine為設置這個textview將在一行中顯示,而不會進行折疊行的效果。
focusable為設置第一個焦點,
focusableInTouchMode為配套focus使用的一個布局,
ellipsize為一個橫向滾動的一個效果。
OK,在這里的話運行我們的demo就已經有了跑馬燈的效果了。
但是,,,
如果要在一個界面中運行多個跑馬燈時,這樣顯然就不可以了,比如我們開一個Linearlayout的兩個textview,那么就只有上面的一個textview有跑馬燈的效果,這是因為,我們在第一個textview中就已經默認占用了focusable這個聚焦的參數,那么我們就需要在java代碼中來實現這個問題,。
首先,創建一個類MarqureeTextView,它繼承的是TextView這個類,利用android studio的強大補全功能,隊這歌繼承的類創建所包含的三個函數方法,如下所示:
package com.example.liuenshuo.study1; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * Created by liuenshuo on 2016/11/20. */ public class MarqureeTextView extends TextView { public MarqureeTextView(Context context) { super(context); } public MarqureeTextView(Context context, AttributeSet attrs) { super(context, attrs); } public MarqureeTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public MarqureeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public boolean isFocused(){ return true; } }
其中,最后的isFoused方法為返回所有值都為true。
其次我們要在MainActivity那將要實現跑馬燈效果的TextView控件的頭部換成這個新建類的“包名.類名”,(因為這個布局文件以及被豬Java文件所引用)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.liuenshuo.study1.MainActivity"> <com.example.liuenshuo.study1.MarqureeTextView 就是這里。。。 android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:focusable="true" android:focusableInTouchMode="true" android:ellipsize="marquee" android:id="@+id/text1" android:textSize="15sp" android:textColor="#981111" android:text="@string/hello_world" /> <com.example.liuenshuo.study1.MarqureeTextView //就是這里。。。 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_below="@+id/text1" android:focusable="true" android:focusableInTouchMode="true" android:ellipsize="marquee" android:singleLine="true" android:textSize="15sp" android:text="@string/hello_world2" /> </RelativeLayout
最后運行我們的demo,就可以實現如下跑馬燈的效果:
好的,這個簡單效果就學到這里,謝謝大家。