Android 自定義View之倒計時實例代碼
需求:
大多數app在注冊的時候,都有一個獲取驗證碼的按鈕,點擊后,訪問接口,最終用戶會收到短信驗證碼。為了不多次寫這個獲取驗證碼的接口,下面將它自定義成一個view,方便使用。
分析一下,這是一個TextView,點擊的時候變色,不能再點擊,同時里面的倒計時開始顯示。那么就有了下面的代碼
代碼:
/** * 通過selector選擇器來改變背景,其中倒計時運行時為android:state_enabled="true", * 不顯示倒計時時為android:state_enabled="false"; * */ public class CountDownView extends TextView { private long totalMills = 10 * 1000;//倒計時的總時間,根據需要更改這個值 private long interval = 1000;//倒計時的時間間隔 public CountDownView(Context context) { super(context); } public CountDownView(Context context, AttributeSet attrs) { super(context, attrs); } public CountDownView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private TimeCount mTimeCount; private void startCount(long totalMills, long countDownInterval) { if (mTimeCount == null) mTimeCount = new TimeCount(totalMills, countDownInterval); mTimeCount.start(); } public void start(){ defaultText = getText().toString(); startCount(totalMills, interval); } public void cancel() { if (mTimeCount != null){ mTimeCount.onFinish(); mTimeCount.cancel(); } } String defaultText = "";//獲取到在點擊之前的文本內容 class TimeCount extends CountDownTimer { public TimeCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { setEnabled(false); setText(millisUntilFinished / 1000 + "S"); } @Override public void onFinish() { setEnabled(true); setText(defaultText); } } } 測試代碼:
public class MainActivity extends Activity implements OnClickListener { private CountDownView mCountDownView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mCountDownView = (CountDownView) findViewById(R.id.tv_1); mCountDownView.setOnClickListener(this); findViewById(R.id.tv_2).setOnClickListener(this); } int count = 0; DemoThread thread; @Override public void onClick(View v) { if(v.getId() == R.id.tv_1){ mCountDownView.start(); thread = new DemoThread(); thread.start(); } else if (v.getId() == R.id.tv_2) { mCountDownView.cancel(); System.out.println("wisely 取消倒計時"); } } class DemoThread extends Thread{ @Override public void run() { while (count < 10) { SystemClock.sleep(100); count++; System.out.println("wisely count:" + count); } } } } 總結:
1、使用的時候,為該控件設置點擊事件,然后調用start()方法,剩下的就是你自己的代碼,一般都是聯網調接口。
2、獲取驗證碼的控件背景可以設置為selector選擇器,設置android:state_enabled屬性。上面例子的selector選擇器代碼如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_enabled="true" android:drawable="@color/green"/> <item android:state_enabled="false" android:drawable="@color/red"/> </selector>
3、在退出activity時,記得調用控件的cancel方法銷毀它,否則會造成內存泄露。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答