在android中用跑马灯的效果显示textview
大家好,在我们通常的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,就可以实现如下跑马灯的效果:
好的,这个简单效果就学到这里,谢谢大家。