Update TextView Every Second

前端 未结 9 1259
南旧
南旧 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));
    }
    
    0 讨论(0)
  • 2020-11-29 00:07

    Add following code in your onCreate() method:

    Thread thread = new Thread() {
    
      @Override
      public void run() {
        try {
          while (!thread.isInterrupted()) {
            Thread.sleep(1000);
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                // update TextView here!
              }
            });
          }
        } catch (InterruptedException e) {
        }
      }
    };
    
    thread.start();
    

    This code starts an thread which sleeps 1000 milliseconds every round.

    0 讨论(0)
  • 2020-11-29 00:13

    Use TextSwitcher (for nice text transition animation) and timer instead.

    0 讨论(0)
  • 2020-11-29 00:15

    It's a very old question and I'm sure there are a lot of resources out there. But it's never too much to spread the word to be at the safe side. Currently, if someone else ever want to achieve what the OP asked, you can use: android.widget.TextClock.

    TextClock documentation here.

    Here's what I've used:

    <android.widget.TextClock
        android:id="@+id/digitalClock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:timeZone="GMT+0000" <!--Greenwich -->
        android:format24Hour="dd MMM yyyy   k:mm:ss"
        android:format12Hour="@null"
        android:textStyle="bold"
        android:layout_alignParentEnd="true" />
    
    0 讨论(0)
  • 2020-11-29 00:16

    You can use Timer instead of Thread. This is whole my code

    package dk.tellwork.tellworklite.tabs;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import dk.tellwork.tellworklite.MainActivity;
    import dk.tellwork.tellworklite.R;
    
    @SuppressLint("HandlerLeak")
    public class HomeActivity extends Activity {
        Button chooseYourAcitivity, startBtn, stopBtn;
        TextView labelTimer;
        int passedSenconds;
        Boolean isActivityRunning = false;
        Timer timer;
        TimerTask timerTask;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.tab_home);
    
            chooseYourAcitivity = (Button) findViewById(R.id.btnChooseYourActivity);
            chooseYourAcitivity.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //move to Activities tab
                    switchTabInActivity(1);
                }
            });
    
            labelTimer = (TextView)findViewById(R.id.labelTime);
            passedSenconds = 0;
    
            startBtn = (Button)findViewById(R.id.startBtn);
            startBtn.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    if (isActivityRunning) {
                        //pause running activity
                        timer.cancel();
                        startBtn.setText(getString(R.string.homeStartBtn));
                        isActivityRunning = false;
                    } else {
                        reScheduleTimer();
                        startBtn.setText(getString(R.string.homePauseBtn));
                        isActivityRunning = true;
                    }
                }
            });
    
            stopBtn = (Button)findViewById(R.id.stopBtn);
            stopBtn.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    timer.cancel();
                    passedSenconds = 0;
                    labelTimer.setText("00 : 00 : 00");
                    startBtn.setText(getString(R.string.homeStartBtn));
                    isActivityRunning = false;
                }
            });
        }
    
        public void reScheduleTimer(){
            timer = new Timer();
            timerTask = new myTimerTask();
            timer.schedule(timerTask, 0, 1000);
        }
    
        private class myTimerTask extends TimerTask{
            @Override
            public void run() {
                // TODO Auto-generated method stub
                passedSenconds++;
                updateLabel.sendEmptyMessage(0);
            }
        }
    
        private Handler updateLabel = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                //super.handleMessage(msg);
    
                int seconds = passedSenconds % 60;
                int minutes = (passedSenconds / 60) % 60;
                int hours = (passedSenconds / 3600);
                labelTimer.setText(String.format("%02d : %02d : %02d", hours, minutes, seconds));
            }
        };
    
        public void switchTabInActivity(int indexTabToSwitchTo){
            MainActivity parentActivity;
            parentActivity = (MainActivity) this.getParent();
            parentActivity.switchTab(indexTabToSwitchTo);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 00:22

    If you want to show time on textview then better use Chronometer or TextClock

    Using Chronometer:This was added in API 1. It has lot of option to customize it.

    Your xml

    <Chronometer
        android:id="@+id/chronometer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp" />
    

    Your activity

    Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
    mChronometer.setBase(SystemClock.elapsedRealtime());
    mChronometer.start();
    

    Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.

    Your xml

    <TextClock
        android:id="@+id/textClock"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:format12Hour="hh:mm:ss a"
        android:gravity="center_horizontal"
        android:textColor="#d41709"
        android:textSize="44sp"
        android:textStyle="bold" />
    

    Thats it, you are done.

    You can use any of these two widgets. This will make your life easy.

    0 讨论(0)
提交回复
热议问题