灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:4493回复:0

Android TextView文字横向自动滚动(跑马灯)

楼主#
更多 发布于:2012-09-06 13:56


TextView实现文字滚动需要以下几个要点:
1.文字长度长于可显示范围:AndroidingleLine="true"
2.设置可滚到,或显示样式:Android:ellipsize="marquee"
3.TextView只有在获取焦点后才会滚动显示隐藏文字,因此需要在包中新建一个类,继承TextView。重写isFocused方法,这个方法默认行为是,如果TextView获得焦点,方法返回true,失去焦点则返回false。跑马灯效果估计也是用这个方法判断是否获得焦点,所以把它的返回值始终设置为true。

java语言: AlwaysMarqueeTextView 类
public class AlwaysMarqueeTextView extends TextView {
public AlwaysMarqueeTextView(Context context) {
super(context);
}
public AlwaysMarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AlwaysMarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean isFocused() {
return true;
}
在布局XML文件中加入这么一个AlwaysMarqueeTextView,这个加入方法也是刚刚学的。
XML语言: layout.xml
<com.examples.AlwaysMarqueeTextView
Android:id=“@+id/AMTV1″
Android:layout_width=“fill_parent”
Android:layout_height=“wrap_content”
Android:lines=“1″
Android:focusable=“true”
Android:focusableInTouchMode=“true”
AndroidcrollHorizontally=“true”
Android:marqueeRepeatLimit=“marquee_forever”
Android:ellipsize=“marquee”
Android:background=“@Android:color/transparent”
/>
ellipsize属性
设置当文字过长时,该控件该如何显示。有如下值设置:”start”—–省略号显示在开头;”end”——省略号显示在结尾;”middle”—-省略号显示在中间;”marquee” ——以跑马灯的方式显示(动画横向移动)
marqueeRepeatLimit属性
在ellipsize指定marquee的情况下,设置重复滚动的次数,当设置为marquee_forever时表示无限次。
组合View的问题:
XML语言: 组合View
< LinearLayout
xmlns:Android =“http://schemas.android.com/apk/res/android
Android:orientation =“vertical”
Android:gravity =“center_vertical”
Android:background =“@drawable/f_background”
Android:layout_width =“fill_parent”
Android:focusable =“true”
Android:layout_height =“50px” >
< TextView
Android:id =“@+id/info_text”
Android:focusable =“true”
Android:layout_width =“fill_parent”
Android:layout_height =“wrap_content”
Android:text =“test marquee  .. “
Android:textColor =“@color/black”
AndroidingleLine =“true”
Android:ellipsize =“marquee”
Android:marqueeRepeatLimit =“3″
Android:textSize =“18sp”
/>
< TextView
Android:id =“@+id/date_text”
Android:layout_width =“fill_parent”
Android:layout_height =“wrap_content”
Android:layout_gravity =“bottom”
Android:textColor =“@color/gray”
Android:text =“2010/05/28″
Android:textSize =“12sp”
/>
</ LinearLayout >
上面示例中2个TextView组合为一个View,由于设置了LinearLayout为focusable而TextView就没法取得焦点了,这样 这个TextView的跑马灯效果就显示不出来,就算你也设置TextView的 Android:focusable="true" 也是 没用的. 这个时候就要使用addStatesFromChildren 这个属性了,在LinearLayout中设置这个属性,然后设置TextView的focusable= "true" 就可以了.关于 addStatesFromChildren的说明:
Sets whether this ViewGroup's drawable states also include its children's drawable states.




喜欢0 评分0
游客

返回顶部