Come posso visualizzare la data e l'ora attuali in un'applicazione Android?
Ok, non è così difficile visto che ci sono diversi metodi per farlo. Suppongo che tu voglia mettere la data e l'ora correnti in una TextView
.
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
C'è altro da leggere nella documentazione che può essere facilmente trovata qui . Lì troverai maggiori informazioni su come cambiare il formato utilizzato per la conversione.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {}
}
});
}
class CountDownRunner implements Runnable{
// @Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
Le scelte ovvie per la visualizzazione dell'ora sono la Vista AnalogClock
e la Vista DigitalClock
.
Per esempio, il seguente layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<AnalogClock
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<DigitalClock
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20sp"/>
</LinearLayout>
Sembra così: