Update TextView Every Second

前端 未结 9 1317
南旧
南旧 2020-11-28 23:58

I\'ve looked around and nothing seems to be working from what I\'ve tried so far...

    @Override
protected void onCreate(Bundle savedInstanceState) {
    su         


        
9条回答
  •  没有蜡笔的小新
    2020-11-29 00:05

    Extending @endian 's answer, you could use a thread and call a method to update the TextView. Below is some code I made up on the spot.

    java.util.Date noteTS;
    String time, date;
    TextView tvTime, tvDate;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.deskclock);
    
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvDate = (TextView) findViewById(R.id.tvDate);
    
        Thread t = new Thread() {
    
            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateTextView();
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };
    
        t.start();
    }
    
    private void updateTextView() {
        noteTS = Calendar.getInstance().getTime();
    
        String time = "hh:mm"; // 12:00
        tvTime.setText(DateFormat.format(time, noteTS));
    
        String date = "dd MMMMM yyyy"; // 01 January 2013
        tvDate.setText(DateFormat.format(date, noteTS));
    }
    

提交回复
热议问题