一、首先要创建一个自定义的TextView
- 创建一个继承TextView的控件
- 资源布局中引用该控件
创建自定义的TextView控件
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class TimerTextView extends TextView {
public TimerTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TimerTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimerTextView(Context context) {
super(context);
}
}
在布局中引用该控件
<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"
tools:context="${relativePackage}.${activityClass}" >
<com.example.timertextviewdemo.TimerTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
二、完善这个TimerTextView加入倒计时功能。
要另启用一个线程,来实现倒计时的功能。首先要实现Runnable接口。为了控制这个倒计时,需要有个isRun变量,查看程序是否正在运行。提供一个start和stop方法来控制计时器。
第二部主要实现倒计时功能。需要一个setTimes和countdown方法。如下:
imp