目的:实现两行长字段的滚动显示。
实现:
1. 在layout布局里边设置三个属性:
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
第一条是设置字段为单行显示;
第二条是是当文字长度超过textview宽度时的显示方式;
android:ellipsize=”start”—–省略号显示在开头 "...pedia"
android:ellipsize=”end”——省略号显示在结尾 "encyc..."
android:ellipsize=”middle”—-省略号显示在中间 "en...dia"
android:ellipsize=”marquee”–以横向滚动方式显示(需获得当前焦点时)
第三条是允许获取焦点;
第四条是触摸时获得焦点;
2.自定义一个TixtView的类,并实现他的三个构造函数,(右键-->source-->里边),其次要重载isFocused的方法,让他return true ;
3.在layout中使用包名+类名来使用,<com.example.marqueetestviewdemo.MarqueeText
完整代码如下:
1.新建类MarqueeText.java 中
package com.example.marqueetestviewdemo;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MarqueeText extends TextView{
public MarqueeText(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MarqueeText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MarqueeText(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public boolean isFocused() {
// TODO Auto-generated method stub
return true;
}
}
2.activity_main.xml中:
<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.marqueetestviewdemo.MainActivity" >
<com.example.marqueetestviewdemo.MarqueeText
android:id="@+id/testview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="@string/hello_world" />
<com.example.marqueetestviewdemo.MarqueeText
android:layout_below="@id/testview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="@string/hello_world" />
</RelativeLayout>
最后显示运行效果: