简体   繁体   中英

How to show the live DateTime as a textView (Like a digital watch) in Android Studio?

I have made two textView in an xml file where one textView shows current date and another shows current time as text .

Now, I have used the java Calendar.getInstance().getTime() method to get the date & time information. But it is acting as a static view ie it is not changing the date & time like a digital clock.

Now I am trying to show the textViews to show the current date & time in synchronization with device-system's date & time. That means, suppose now it is 11:59:59 PM in the night and the date is 7th Sep, 2022 . Just after 1s , my time textView should show the time as 12:00:00 AM and date should show as 8th Sep, 2022 . And it should continue to change the time after every 1s like a digital clock. Last of all, there should not be any delay in between system dateTime & app dateTime ie perfectly synchronised.

How to do that??

public class MainActivity extends AppCompatActivity {

    TextView textDate, textClock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textDate = findViewById(R.id.textDate);
        textClock = findViewById(R.id.textClock);
        setDateTime();
    }

    private void setDateTime() {
        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy", Locale.getDefault());
        SimpleDateFormat df_clock = new SimpleDateFormat("hh:mm:ss a", Locale.getDefault());
        String formattedDate = df.format(c);
        String formattedClock = df_clock.format(c);

        textDate.setText(formattedDate);
        textClock.setText(formattedClock);
    }
}

There's already a TextClock class in Android which you should be able to use. Try replacing your two TextView s with these and set the formats to your patterns.

You need to set up a background thread that will ask the UI to update itself every second.

I think something like this (but I don't know how accurate this will be)

private void blink() {
      final Handler hander = new Handler();
      new Thread(new Runnable() {
         @Override
         public void run() {
            // off the UI
            try {
               Thread.sleep(1000);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
            // back ot the UI
            hander.post(new Runnable() {
               @Override
               public void run() {
                  // notify the UI here
                  blink();
               }
            });
         }
      }).start();
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM