Android Studio 多线程实现 每隔一秒使text的值加1
Posted SEMHAQ
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Studio 多线程实现 每隔一秒使text的值加1相关的知识,希望对你有一定的参考价值。
实现功能:创建一个TextView,居中显示,text设置为0。主线程中开启新的线程,每隔1秒使text的值加1
MainActivity.java
package com.example.test4;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
public class MainActivity extends AppCompatActivity
private TextView number;
private int num = 0;
private boolean flag = true;
Thread thread = new Thread(new Runnable()
@Override
public void run()
while (flag)
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
try
thread.sleep(1000);
catch (InterruptedException e)
e.printStackTrace();
);
private Handler handler = new Handler()
@Override
public void handleMessage(Message msg)
switch (msg.what)
case 1:
number.setText(String.valueOf(++num));
break;
default:
break;
;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number = findViewById(R.id.textView);
thread.start();
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textview"
android:textSize="96sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test4">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
以上是关于Android Studio 多线程实现 每隔一秒使text的值加1的主要内容,如果未能解决你的问题,请参考以下文章
如何:每隔一秒调用一个方法来实现 getchar() 或者如果它为空则继续