?Android?,TextClock?????????????/????????TextClock?????,?????Handler
?Runnable
???????????,??????TextClock???????5?:
- ?????(??activity_main.xml)?????TextClock??:
- ?Activity(??MainActivity.java)?,??Handler?Runnable???????:
import android.os.Handler; import android.os.SystemClock; import android.widget.TextClock; public class MainActivity extends AppCompatActivity { private TextClock textClock; private Handler handler; private Runnable runnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textClock = findViewById(R.id.textClock); // ????Handler?? handler = new Handler(); // ????Runnable??,????TextClock??? runnable = new Runnable() { @Override public void run() { updateTextClock(); handler.postDelayed(this, 5000); // ?5????? } }; // ????TextClock??? handler.post(runnable); } private void updateTextClock() { // ?????? String currentTime = getCurrentTime(); // ??TextClock??? textClock.setFormat24Hour(currentTime); } private String getCurrentTime() { // ?????????????? return String.format("d:d", SystemClock.elapsedRealtime() / 1000 % 24, SystemClock.elapsedRealtime() / 1000 % 60); } }
??????,???????Handler?????Runnable???Runnable????????updateTextClock
???,??????????????TextClock??????,????handler.postDelayed(this, 5000)
?Runnable?????Handler?,???5????????,????handler.post(runnable)
????TextClock????