美文网首页
Handler,

Handler,

作者: 被罚站的树 | 来源:发表于2020-04-27 15:56 被阅读0次
image.png
image.png
image.png
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    tools:context=".MainActivity">

    <ProgressBar
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:id="@+id/timer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="10"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="200dp"
        />
</RelativeLayout>

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ProgressBar timer;//声明水平进度条
    private int Time=10;//定义时间长度为60
    private int mProgressStatus=0;//定义初始完成进度为0;
    final int T_msg=0x11;//消息代码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timer=findViewById(R.id.timer);
        //启动进度条
        handler.sendEmptyMessage(T_msg);

    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(Time-mProgressStatus>0) {//倒计时设置判断,当前进度大于0
                mProgressStatus++;//进度+1
                timer.setProgress(Time-mProgressStatus);//更新组件进度
                sendEmptyMessageDelayed(T_msg,1000);//每一秒发送一次消息
            }else {
                Toast.makeText(MainActivity.this, "时间到", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
image.png image.png
image.png

相关文章

网友评论

      本文标题:Handler,

      本文链接:https://www.haomeiwen.com/subject/ixowfctx.html