Andrews updated at regular intervals in the interface, for example to display the current time

I. Description

Only you need to override the message processing method Handler class, when a thread starts transmitting a new message, the message processing method Handler class will be automatically called back.

Second, the code

  1. java code
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity
{
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=findViewById(R.id.tv);//文本框的实例化


        final Handler handler=new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                if (msg.what==0x1233)//如果消息是本程序所发送的
                {
                    Date date=new Date();
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = simpleDateFormat.format(date);
                    tv.setText(format);

                }
                super.handleMessage(msg);
            }
        };

        //使用定时器,每隔1000毫秒发送一个消息
        new Timer().schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                Message message=new Message();
                message.what=0x1233;
                handler.sendMessage(message);

            }
        },0,1000);

    }
}

  1. Interface code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>

Third, the effect screenshots

Here Insert Picture Description

Published 33 original articles · won praise 0 · Views 1410

Guess you like

Origin blog.csdn.net/Deep_rooted/article/details/104632813