TextView不用获取焦点也能实现跑马灯
1.写一个类继承TextView
- package com.example.tt;
- import android.content.Context;
- import android.graphics.Rect;
- import android.util.AttributeSet;
- import android.widget.TextView;
- public class ScrollingTextView extends TextView {
- public ScrollingTextView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
- public ScrollingTextView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- public ScrollingTextView(Context context) {
- super(context);
- }
- @Override
- protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
- if(focused)
- super.onFocusChanged(focused, direction, previouslyFocusedRect);
- }
- @Override
- public void onWindowFocusChanged(boolean focused) {
- if(focused)
- super.onWindowFocusChanged(focused);
- }
- @Override
- public boolean isFocused() {
- return true;
- }
- }
2.xml 中增加属性
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <com.example.tt.ScrollingTextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginLeft="80dip"
- android:layout_marginBottom="25dip"
- android:textSize="25sp"
- android:singleLine="true"
- android:textColor="@android:color/black"
- android:ellipsize="marquee"
- android:focusable="true"
- android:marqueeRepeatLimit="marquee_forever"
- android:focusableInTouchMode="true"
- android:scrollHorizontally="true"
- android:text="这才是真正的文字跑马灯效果,文字移动速度,文字移动方向,文字移动的样式,动画等等……"
- android:background="#2FFFFFFF" />
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" />
- </LinearLayout>
3. 在activity中声明
- package com.example.tt;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- }