目的: 做一个包含进度条控件的App,要求用Java代码实现进度条的动态效果。
方法简介: 界面使用了RelativeLayout布局,其中嵌套了一个ProgressBar控件、一个TextView控件和一个Button控件。
使用线程模拟文件上传进度,目的是实现点击上传按钮ProgressBar进行不断增长,TextView会显示当前进度所占百分比,当上传实现100%之后会弹出“上传完成!”的Toast。
动态进度条实现:
activity_mian.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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/pgBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:max="100" />
<TextView
android:id="@+id/textView"
android:layout_below="@+id/pgBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textSize="20dp"
android:text="当前上传进度为:0%"/>
<Button
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="上传" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java:
package com.example.progressbar;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private ProgressBar mpgbar;
private Button mbt;
private Handler handler;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mpgbar = findViewById(R.id.pgBar);
mbt = findViewById(R.id.button);
mTextView = findViewById((R.id.textView));
handler = new MyHandler();
final int pg;
pg = 50;
mbt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread me = new Thread(new mthread());
me.start();
}
});
}
class mthread implements Runnable {
int i = 1;
@Override
public void run() {
while (i <= 100) {
Message message = Message.obtain();
message.arg1 = i;
handler.sendMessage(message);
mpgbar.setProgress(i);
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int arg1 = msg.arg1;
mTextView.setText("当前上传进度为:" + arg1 + "%");
if (arg1 == 100) {
Toast.makeText(MainActivity.this, "上传完成!", Toast.LENGTH_SHORT).show();
}
}
}
}