android TextView实现跑马灯效果
Posted showCar
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android TextView实现跑马灯效果相关的知识,希望对你有一定的参考价值。
最近忙着项目,很久没有总结提交博客和提交github了。接下来我打算整理下项目中用到的比较有用的发表到博客上。也打算总结一些关于设计模式和源码分析的博客。今天的话就先来讲下一个非常简单但又很常用的控件,跑马灯状态的TextView。当我的要显示的文本长度太长,又不想换行时用它来显示文本一来可以完全的显示出文本,二来效果也挺酷,实现起来超级简单,所以,何乐不为。先看下效果图:
代码实现
TextView自带了跑马灯功能,只要把它的ellipsize属性设置为marquee就可以了。但有个前提,就是TextView要处于被选中状态才能有效果,看到这,我们就很自然的自定义一个控件,写出以下代码:
public class MarqueeTextView extends TextView
public MarqueeTextView(Context con)
super(con);
public MarqueeTextView(Context context, AttributeSet attrs)
super(context, attrs);
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle)
super(context, attrs, defStyle);
@Override
public boolean isFocused()
// TODO Auto-generated method stub
if(getEditableText().equals(TruncateAt.MARQUEE))
return true;
return super.isFocused();
重写了isFocused方法,并进行判断,只有设置了marqueen属性的才保持选中状态,否则它就跟普通TextView一样。接下来就可以直接使用了,看下布局:
<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">
<FrameLayout
android:id="@+id/titlebar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#39ac69" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffffff"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:id="@+id/home_location_iv"
android:layout_width="25dp"
android:layout_height="27dp"
android:layout_marginLeft="10dp"
android:scaleType="fitXY"
android:src="@drawable/icon_place" />
<com.lxj.marqueetextview.MarqueeTextView
android:id="@+id/home_location_tv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="正在定位..."
android:textColor="#39ac69"
android:textSize="18sp" />
<ImageView
android:id="@+id/home_search_iv"
android:layout_width="25dp"
android:layout_height="27dp"
android:layout_marginRight="10dp"
android:scaleType="fitXY"
android:src="@drawable/icon_place" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
要注意两点ellipsize属性要设置为”marquee”,行数属性即singleLine要设置为true。到此TextView的跑马灯效果就实现了。
以上是关于android TextView实现跑马灯效果的主要内容,如果未能解决你的问题,请参考以下文章