转载请注明
http://blog.csdn.net/u012184853/article/details/50129121
首先讨论下,android自带textview跑马灯的实现,需要哪些参数,其中比较烦人的就是,需要TextView获得焦点,跑马灯才能有效果,所以我们在对于布局gone掉,或者在ListView,ScrollView中跑马灯经常没有效果,无法获得焦点找原因,干脆就自己写一个,而且能实现复杂的需求
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
/>
自定义跑马灯控件
import java.util.List;
import android.content.Context;
import android.graphics.Paint;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;
public class MarqueeText extends TextView implements Runnable{
private int currentScrollX;
private boolean isStop = false;
private int textWidth;
private List<String> mList;
private final int REPEAT = 1;
private int repeatCount = 0;
private int currentNews = 0;
public MarqueeText(Context context) {
super(context);
init();
}
public MarqueeText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MarqueeText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void init(){
setClickable(true);
setSingleLine(true);
setEllipsize(TruncateAt.MARQUEE);
setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
}
public void setData(List<String> mList){
if(mList == null || mList.size()==0){
return;
}
this.mList = mList;
currentNews = 0;
String n = mList.get(currentNews);
setText(n);
setTag(n);
startScroll();
}
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
MeasureTextWidth();
}
@Override
public void onScreenStateChanged(int screenState) {
super.onScreenStateChanged(screenState);
if(screenState == SCREEN_STATE_ON){
startScroll();
}else{
stopScroll();
}
}
/**
* 获取文字宽度
*/
private void MeasureTextWidth() {
Paint paint = this.getPaint();
String str = this.getText().toString();
textWidth = (int) paint.measureText(str);
}
@Override
public void run() {
if(textWidth < 1){
if(mList != null && mList.size() > 0){
nextNews();
}else{
return;
}
}
currentScrollX += 1;// 滚动速度
scrollTo(currentScrollX, 0);
if (isStop) {
return;
}
if (getScrollX() >= textWidth) {
currentScrollX = -getWidth();
scrollTo(currentScrollX, 0);
if(repeatCount >= REPEAT){
nextNews();
}else{
repeatCount ++;
}
}
postDelayed(this, 10);
}
private void nextNews(){
repeatCount = 0;
currentNews ++;
currentNews = currentNews%mList.size();
String n = mList.get(currentNews);
setText(n);
setTag(n);
}
// 开始滚动
public void startScroll() {
isStop = false;
this.removeCallbacks(this);
post(this);
}
// 停止滚动
public void stopScroll() {
isStop = true;
}
}
源码下载地址