参考: http://blog.youkuaiyun.com/sky181772733/article/details/7003125
在TextView中文本过长又需要单行显示(比如在ListView中)的情况,需要使用跑马灯效果。跑马灯效果是怎么实现的呢
1、首先看一个多行文本的效果

布局如下
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="28sp" />
2、将这个多行文本设置为单行

布局如下
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="@string/hello_world"
android:textSize="28sp" />
3、使用marquee得到跑马灯效果

布局如下
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:text="@string/hello_world"
android:textSize="28sp" />
仍然没有跑马灯效果
4、跑马灯效果需要当前TextView能够获得焦点
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="@string/hello_world"
android:textSize="28sp" />
可以实现跑马灯效果了
5、在不设置focusable和focusableInTouchMode属性为true的情况下,也可以在Java代码中选中TextView触发跑马灯效果
findViewById(R.id.textView).setSelected(true);
6、ListView中TextView要实现跑马灯效果,通过设置focusable和focusableInTouchMode为true不起作用,需要直接将TextView设置为selected,代码如下:
list_item布局
<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" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:textSize="28sp" />
</RelativeLayout>
Java代码
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.textView1) {
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setSelected(true);
return v;
}
};
adapter.add("超长的文本超长的文本超长的文本");
getListView().setAdapter(adapter);
}
}

(晕,全跑起来了。。。)
总结:
1、可以通过设置TextView的focusable和focusableInTouchMode为true,或者selected为true来触发长文本的跑马灯效果
2、上面跑马灯效果只有一次,如果需要无限次可设置android:marqueeRepeatLimit="marquee_forever"
3、ListView最好只有当前选中项才触发跑马灯效果,否则用户体验相当糟糕

本文详细介绍了如何在Android中实现跑马灯效果,包括设置TextView属性实现单行文本滚动显示,以及在ListView中使特定项拥有此效果的方法。
1430

被折叠的 条评论
为什么被折叠?



