本文實例為大家分享了Android實現倒計時功能的具體代碼,供大家參考,具體內容如下
1、實現效果
如下圖所示:
2、代碼實現
新建一個名為CountdownTime的項目,activity_main.xml代碼如下:
<?xml version="1.0" encoding="utf-8"?><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=".MainActivity"> <TextView android:id="@+id/countdownTimeTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/maxTime" android:textSize="60sp" /></RelativeLayout>
MainActivity.class代碼如下:
public class MainActivity extends AppCompatActivity { /** * 倒計時標記 */ public static final int COUNTDOWN_TIME_CODE = 99999; /** * 倒計時間隔 */ public static final int DELAY_MILLIS = 1000; /** * 倒計時最大值 */ public static final int MAX_COUNT = 10; /** * 文本控件 */ private TextView countdownTimeTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化文本控件 countdownTimeTextView = findViewById(R.id.countdownTimeTextView); //創建一個handler CountdownTimeHandler handler = new CountdownTimeHandler(this); //新建一個message Message message = Message.obtain(); message.what = COUNTDOWN_TIME_CODE; message.arg1 = MAX_COUNT; //第一次發送message handler.sendMessageDelayed(message, DELAY_MILLIS); } public static class CountdownTimeHandler extends Handler { /** * 倒計時最小值 */ public static final int MIN_COUNT = 0; //創建MainActivity弱引用 final WeakReference<MainActivity> mWeakReference; public CountdownTimeHandler(MainActivity activity) { this.mWeakReference = new WeakReference<>(activity); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); //獲取對MainActivity的弱引用 MainActivity activity = mWeakReference.get(); switch (msg.what) { case COUNTDOWN_TIME_CODE: int value = msg.arg1; activity.countdownTimeTextView.setText(String.valueOf(value--)); //循環發送消息的控制 if (value >= MIN_COUNT) { Message message = Message.obtain(); message.what = COUNTDOWN_TIME_CODE; message.arg1 = value; sendMessageDelayed(message, DELAY_MILLIS); } break; } } }}
3、快捷鍵總結
Ctrl+Alt+F:改變變量的域
Ctrl+Alt+T:surrounded with快捷鍵
Ctrl+P:查看方法的參數
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答