一分钟实现 Android textview 跑马灯文字滚动效果

时间:2021-11-17 05:58:04

*文字水平跑马灯效果:

设置如下TextView控件文件的XML:

<com.example.Mytext
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="20dp"
android:gravity="center"
android:singleLine="true"//限制行数为1行
android:ellipsize="marquee"//marquee 文字滚动
android:marqueeRepeatLimit="marquee_forever"//文字滚动次数:marquee_forever 无限次
android:focusable="true"//获取焦点
android:focusableInTouchMode="true"//获取触摸焦点
android:textColor="@color/red"
android:text="@string/text"
/>

有其它布局如ScrollView等抢占焦点,需要自定义控件获取焦点:

public class Mytext extends TextView {  
public Mytext(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFocusChanged(boolean focused, int direction,
Rect previouslyFocusedRect) {
if(focused){
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if(hasWindowFocus){
super.onWindowFocusChanged(hasWindowFocus);
}
}
@Override
public boolean isFocused() {
return true;
}
}

*文字切换动画效果:

 1 public class MainActivity extends Activity {
2 private static final String[] TEXTS = { "First", "Second", "Third" };
3 private int mTextsPosition = 0;
4 private TextSwitcher mTextSwitcher;
5 @Override
6 public void onCreate(Bundle savedInstanceState) {
7 super.onCreate(savedInstanceState);
8 setContentView(R.layout.main);
9 mTextSwitcher = (TextSwitcher) findViewById(R.id.your_textview);
10 mTextSwitcher.setFactory(new ViewFactory() {
11 @Override
12 public View makeView() {
13 System.out.println("makeView");
14 TextView t = new TextView(MainActivity.this);
15 t.setGravity(Gravity.CENTER);//t.setTextColor(Color.BLACK);
16 return t;
17 }
18 });
19 mTextSwitcher.setInAnimation(this, android.R.anim.fade_in);
20 mTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);
21 onSwitchText(null);
22 }
23 public void onSwitchText(View v) {
24 mTextSwitcher.setText(TEXTS[mTextsPosition]);
25 setNextPosition();
26 }
27 private void setNextPosition() {
28 mTextsPosition = (mTextsPosition + 1) % TEXTS.length;
29 }
30 }