使用Kotlin的Android ProgressBar

怀飞扬
2023-12-01

In this tutorial, we’ll discuss and implement ProgressBar in our Android Application using Kotlin.

在本教程中,我们将使用Kotlin在Android应用程序中讨论和实现ProgressBar。

什么是ProgressBar? (What is a ProgressBar?)

ProgressBar UI element is used to display the Progress on the app screen. We can use a ProgressBar to show the download/upload progress on the app screen.

ProgressBar UI元素用于在应用程序屏幕上显示进度。 我们可以使用ProgressBar在应用程序屏幕上显示下载/上传进度。

进度条类型 (Progress Bar Types)

There are two types of Progress Bar.

有两种类型的进度栏。

  1. Determinate ProgressBar – This is used when you can track and show the progress completed.

    确定的ProgressBar –当您可以跟踪和显示完成的进度时使用。
  2. Indeterminate ProgressBar – This one goes infinitely until stopped.

    不确定的ProgressBar –此无限进行直到停止。

A ProgressDialog would hold a ProgressBar inside an Alert Dialog. ProgressDialog is now deprecated since it isn’t a good idea to show long progress in a dialog while blocking the screen.

ProgressDialog将在Alert对话框中保存一个ProgressBar。 现在不推荐使用ProgressDialog,因为在阻塞屏幕时在对话框中显示长时间的进度并不是一个好主意。

ProgressBar属性 (ProgressBar Attributes)

Some of the important attributes of ProgressBar are:

ProgressBar的一些重要属性是:

  • android:indeterminate – used to specify the boolean value indicating the type of the ProgressBar

    android:indeterminate –用于指定指示ProgressBar类型的布尔值
  • android:max – The upper limit of the progress

    android:max –进度上限
  • android:min – The lower limit of the progress

    android:min –进度的下限
  • android:progress – The steps by which the progress would be incremented.

    android:progress –逐步增加android:progress的步骤。
  • android:minWidth and minHeight – Used to define the dimensions of the ProgressBar

    android:minWidthminHeight –用于定义ProgressBar的尺寸
  • android:progressBarTint – The tint color of the progress completed of the ProgressBar

    android:progressBarTint – ProgressBar完成android:progressBarTint的色调颜色
  • android:progressBarBackgroundTint – The tint color of the progress completed of the ProgressBar

    android:progressBarBackgroundTint -ProgressBar完成android:progressBarBackgroundTint的色调颜色
  • style – Used to set the style of the ProgressBar. By default it is circular. We can set the style as @style/Widget.AppCompat.ProgressBar.Horizontal for the Horizontal ProgressBar

    style –用于设置ProgressBar的样式。 默认情况下为圆形。 我们可以将Horizo​​ntal ProgressBar的样式设置为@style/Widget.AppCompat.ProgressBar.Horizontal
  • android:progressDrawable – Is used to set a drawable for the progress.

    android:progressDrawable –用于设置进度的可绘制对象。
  • android:secondaryProgress – Indicates the secondary progress value. This is used when we want to show the sub-downloads/subtasks progress.

    android:secondaryProgress –指示辅助进度值。 当我们要显示子下载/子任务进度时,将使用此方法。

The default tint colors are set to the colorAccent defined in the styles.xml.

默认的颜色设置为styles.xml定义的colorAccent

ProgressBar XML布局 (ProgressBar XML Layout)

A basic circular indeterminate ProgressBar XML layout looks like this:

基本的圆形不确定ProgressBar XML布局如下所示:

<ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        android:minWidth="50dp" />

In the following section, we’ll implement various types of ProgressBars in our Android app using Kotlin.

在以下部分中,我们将使用Kotlin在Android应用程序中实现各种类型的ProgressBar。

Android ProgressBar Kotlin App项目结构 (Android ProgressBar Kotlin App Project Structure)

1. XML布局代码 (1. XML Layout Code)

The code for the activity_main.xml layout is as follows.

activity_main.xml布局的代码如下。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        android:minWidth="50dp" />


    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        android:minHeight="50dp"
        android:minWidth="200dp" />


    <TextView
        android:id="@+id/textViewHorizontalProgress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0" />


    <ProgressBar
        android:id="@+id/progressBarHorizontal"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="100"
        android:minHeight="50dp"
        android:minWidth="200dp"
        android:progress="1"
        android:progressBackgroundTint="@android:color/darker_gray"
        android:progressTint="@color/colorPrimary" />


    <Button
        android:id="@+id/btnProgressBarHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="horizontalDeterminate"
        android:text="DETERMINATE HORIZONTAL PROGRESS BAR" />


    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ProgressBar
            android:id="@+id/progressBarSecondary"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:minHeight="150dp"
            android:padding="8dp"
            android:minWidth="150dp"
            android:progressDrawable="@drawable/progress_states" />

        <TextView
            android:id="@+id/textViewPrimary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#000" />

        <TextView
            android:id="@+id/textViewSecondary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:layout_below="@+id/progressBarSecondary"
            android:textColor="@color/colorPrimaryDark" />


    </RelativeLayout>

    <Button
        android:id="@+id/btnProgressBarSecondary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DETERMINATE SECONDARY PROGRESS BAR" />


</LinearLayout>

In the last progress bar, we’ve set a progress drawable on the horizontal ProgressBar.

在最后一个进度栏中,我们在水平ProgressBar上设置了一个可绘制的进度。

The drawable.xml file is progress_states.xml.

drawable.xml文件是progress_states.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape android:shape="oval">
            <stroke
                android:width="4dp"
                android:color="@color/colorPrimary" />
            <solid android:color="@android:color/white" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip
            android:clipOrientation="vertical"
            android:gravity="bottom">
            <shape android:shape="oval">
                <stroke
                    android:width="4dp"
                    android:color="@android:color/black" />
                <solid android:color="@android:color/white" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip
            android:clipOrientation="vertical"
            android:gravity="bottom">
            <shape android:shape="oval">
                <stroke
                    android:width="4dp"
                    android:color="@color/colorAccent" />
                <solid android:color="#F288F8" />
            </shape>
        </clip>
    </item>
</layer-list>

In this drawable, we’ve created different states of the drawable.

在此可绘制对象中,我们创建了可绘制对象的不同状态。

All are circular shaped and each layer would be displayed for the different states – idle, secondary progress, primary progress.

所有都是圆形的,每层将针对不同的状态显示-空闲,次要进度,主要进度。

2. Kotlin主要活动代码 (2. Kotlin Main Activity Code)

Let’s look at the MainActivity.kt Kotlin class code.

让我们看一下MainActivity.kt Kotlin类代码。

package net.androidly.androidlyprogressbar

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


    var isStarted = false
    var progressStatus = 0
    var handler: Handler? = null
    var secondaryHandler: Handler? = Handler()
    var primaryProgressStatus = 0
    var secondaryProgressStatus = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        handler = Handler(Handler.Callback {
            if (isStarted) {
                progressStatus++
            }
            progressBarHorizontal.progress = progressStatus
            textViewHorizontalProgress.text = "${progressStatus}/${progressBarHorizontal.max}"
            handler?.sendEmptyMessageDelayed(0, 100)

            true
        })

        handler?.sendEmptyMessage(0)


        btnProgressBarSecondary.setOnClickListener {
            primaryProgressStatus = 0
            secondaryProgressStatus = 0

            Thread(Runnable {
                while (primaryProgressStatus < 100) {
                    primaryProgressStatus += 1

                    try {
                        Thread.sleep(1000)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }

                    startSecondaryProgress()
                    secondaryProgressStatus = 0

                    secondaryHandler?.post {
                        progressBarSecondary.progress = primaryProgressStatus
                        textViewPrimary.text = "Complete $primaryProgressStatus% of 100"

                        if (primaryProgressStatus == 100) {
                            textViewPrimary.text = "All tasks completed"
                        }
                    }
                }
            }).start()
        }

    }

    fun startSecondaryProgress() {
        Thread(Runnable {
            while (secondaryProgressStatus < 100) {
                secondaryProgressStatus += 1

                try {
                    Thread.sleep(10)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

                secondaryHandler?.post {
                    progressBarSecondary.setSecondaryProgress(secondaryProgressStatus)
                    textViewSecondary.setText("Current task progress\n$secondaryProgressStatus% of 100")

                    if (secondaryProgressStatus == 100) {
                        textViewSecondary.setText("Single task complete.")
                    }
                }
            }
        }).start()
    }

    fun horizontalDeterminate(view: View) {
        isStarted = !isStarted
    }

}

The horizontalDeterminate Kotlin function is triggered when the first button is clicked. It is used to start/stop Horizontal ProgressBar.

单击第一个按钮时,将触发horizontalDeterminate Kotlin函数。 用于启动/停止水平进度条。

A Handler is associated with a single thread. It is used to send messages to the Thread.

处理程序与单个线程相关联。 它用于将消息发送到线程。

The btnProgressBarSecondary click triggers the second progress bar. We have created two handlers – one for the normal progress and second for the subtasks. In each of them, we are setting the thread to sleep.

btnProgressBarSecondary单击将触发第二个进度栏。 我们创建了两个处理程序-一个用于正常进度,另一个用于子任务。 在每个线程中,我们都将线程设置为Hibernate状态。

For the secondary thread, the sleep time is 1/100 of the primary progress thread. The progress value is displayed on the TextView.

对于辅助线程,睡眠时间是主要进度线程的1/100。 进度值显示在TextView上。

Output:

输出:

翻译自: https://www.journaldev.com/327/android-progressbar-using-kotlin

 类似资料: