Android 使用AsyncTask实现简单的进度条加载

AsyncTask的简单使用:点击加载按钮后,进度条进行加载,到100%后界面文字改变,进度条隐藏。

一、效果预览图

在这里插入图片描述在这里插入图片描述在这里插入图片描述

二、代码实现

  1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="MainActivity">

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginHorizontal="20dp"
        android:text="Click the button to start."
        android:textSize="20dp"/>

    <ProgressBar
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="20dp"
        style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
        android:visibility="visible"/>

    <Button
        android:id="@+id/btn_downLoad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="50dp"
        android:text="download" />
</LinearLayout>
  1. MainActvity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private ProgressBar bar;
    private TextView tv_show;
    private Button btn_downLoad;
    private load download;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bar = (ProgressBar) findViewById(R.id.bar);
        tv_show = (TextView) findViewById(R.id.tv_show);
        btn_downLoad = (Button) findViewById(R.id.btn_downLoad);

        //set the onClickListener to the button
        btn_downLoad.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                download = new load();
                download.execute();
            }
        });
    }

    //define an AsyncTask
    private class load extends AsyncTask<String, Integer, Void>
    {
        //Begin-can use UI thread here
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            tv_show.setText("Some important data is being collected now.\n"
                    +"Please be patient and wait...");
        }

        //this is the slow background thread taking care of heavy tasks
        //cannot directly change UI
        @Override
        protected Void doInBackground(final String... args )
        {
            for (int i = 1; i <= 100; i++) {
                // refresh the data
                publishProgress(i);
                if(isCancelled()){
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        //periodic updates- it is ok to change UI
        @Override
        protected void onProgressUpdate(Integer... values)
        {
            super.onProgressUpdate(values[0]);
            bar.setProgress(values[0]);
            if(isCancelled())
            {
                return;
            }
            tv_show.setText("loading..." + values[0] + "%");
        }

        // End -can use UI thread here
        @Override
        protected void onPostExecute(final Void result)
        {
            super.onPostExecute(result);
            tv_show.setText("The data is downloaded.");
            bar.setVisibility(View.GONE);
        }
    }
}
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AsyncTaskAndroid 开发中用于在后台执行耗时操作的一个类,可以进行异步操作以避免在主线程上执行耗时操作导致界面卡顿的情况。在 Kotlin 中使用 AsyncTask 的用法与 Java 中基本一致。 使用 AsyncTask 需要创建一个继承于 AsyncTask 的子类来进行异步操作。在 Kotlin 中,可以使用 object 关键字创建一个匿名内部类来实现 AsyncTask 的子类。下面是一个基本的 AsyncTask 使用示例: ```kotlin // 创建一个继承自 AsyncTask 的子类 val task = object : AsyncTask<Void, Void, String>() { // 在后台线程执行耗时操作 override fun doInBackground(vararg params: Void): String { // 执行耗时操作,例如网络请求或数据库查询 return "AsyncTask 执行完毕" } // 在耗时操作结束后更新 UI override fun onPostExecute(result: String) { // 在这里更新 UI,例如更新 TextView 的内容 } } // 执行 AsyncTask task.execute() ``` 在上面的示例中,首先创建了一个继承于 AsyncTask 的子类,并实现了三个方法:doInBackground、onPostExecute 和 onPostExecute。doInBackground 方法用于在后台线程执行耗时操作,例如网络请求或数据库查询,并返回结果给 onPostExecute 方法。onPostExecute 方法在耗时操作结束后会被调用,你可以在这个方法中更新 UI。 最后,通过调用 AsyncTask 的 execute 方法来执行异步操作。 需要注意的是,Kotlin 推荐使用更现代化的异步操作方式,例如使用 Kotlin 协程来替代 AsyncTask。Kotlin 协程提供了更简洁、可读性更高的代码,且在处理异步操作上更加灵活和强大。因此,如果在新的项目中,可以考虑使用 Kotlin 协程来替代 AsyncTask

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值