佈局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- android:focusable="true"也可以不要,因爲自定義的view裏面已經設置了位true,當兩者都設置時,自定義的優先級更高 ,
<span style="white-space:pre"> </span>如果不自定義View,僅僅靠xml屬性設置,後面的textView焦點會被第一個搶奪,從而只有第一個實現跑馬燈效果,後面的不能實現-->
<com.example.exercise.MarqueeTextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:focusableInTouchMode="true"
android:focusable="true"
android:ellipsize="marquee"
android:text="@string/marquee_text"
/>
<com.example.exercise.MarqueeTextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:focusableInTouchMode="true"
android:ellipsize="marquee"
android:text="@string/marquee_text"
/>
</LinearLayout>
自定義的textView<span style="white-space:pre"> </span><pre name="code" class="java">package com.example.exercise;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MarqueeTextView extends TextView {
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MarqueeTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
<span style="white-space:pre"> </span>//主要就是這個方法讓此控件位聚焦狀態
@Override
public boolean isFocused() {
// TODO Auto-generated method stub
return true;
}
}
<pre name="code" class="java">package com.example.exercise;
import android.app.Activity;
import android.os.Bundle;
public class MarqueeTextActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.marquee_textview);
}
}
在配置文件中配置入口:
<activity android:name="com.example.exercise.MarqueeTextActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<span style="white-space:pre">
</span>
</pre><pre name="code" class="java">