运行效果图
在xml中的代码
<?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:background="@drawable/wzz"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:layout_alignParentBottom="true"
android:layout_marginBottom="60dp"
/>
</RelativeLayout>
在java中的代码
package com.example.startgame;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private int mProgress=0;
private Handler mHandler;
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);//设置全屏显示
progressBar=(ProgressBar)findViewById(R.id.progressBar);
mHandler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
if(msg.what==0x111){
progressBar.setProgress(mProgress);
}
else{
Toast.makeText(MainActivity.this,"耗时操作已完成",Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
while(true){
mProgress=doWork();
Message m=new Message();
if(mProgress<100){
m.what=0x111;
mHandler.sendMessage(m);
}
else{
m.what=0x110;
mHandler.sendMessage(m);
break;
}
}
}
private int doWork(){
mProgress+=Math.random()*10;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return mProgress;
}
}).start();
}
}