如何在Android中显示带有百分比的进度条示例

问题描述 投票:0回答:3

我有一个任务是添加一个带有百分比值的

ProgressBar
,以便在用户想要预测某些内容时显示一个值。我没有使用
ProgressDialog
,因为它现在已被弃用。这里,百分比值取决于从开始请求到完成请求的时间。我正在使用
Volley
从服务器获取数据。

这是我想要实现的目标的示例图片:

我已经这样做了

我在警报对话框中实现了水平进度条(我使用这种方式是因为进度对话框已被弃用)。我想像这样设置进度条。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view =  inflater.inflate(R.layout.fragment_result_prediction, container, false);
    predictProgress = (ProgressBar) view.findViewById(R.id.progressbarPredict);
    AlertDialog.Builder(view.getContext());
    builder.setCancelable(false); // if you want user to wait for some process to finish,
    View v = inflater.inflate(R.layout.layout_loading_dialog, null);
    builder.setView(v);
    final AlertDialog dialog = builder.create();
    submitPredictPlant.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                dialog.show();
                predictProgress.setProgress(25);
                predictProgress.setProgress(50);
                predictProgress.setProgress(75);
                predictProgress.setProgress(100);
                dialog.dismiss();

我想在进度为 100 时关闭对话框。但这会给出类似的错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setProgress(int)' on a null object reference

我已经参考了builder.setview中使用的layout_loading_dialog的进度条。

这是layout_loading_dialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="4"
    android:gravity="center"
    android:text="Please wait! This may take a moment." />

<ProgressBar
    android:layout_width="match_parent"
    android:id="@+id/progressbarPredict"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    style="?android:attr/progressBarStyleHorizontal"/>

android progress-bar android-progressbar
3个回答
10
投票

以下是创建带有百分比的进度对话框的代码,如图所示。

int status = 0;
Handler handler = new Handler();

public void showDialog(Activity activity, String msg) {
    final Dialog dialog = new Dialog(activity);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(false);
    dialog.setContentView(R.layout.dialog);

    final ProgressBar text = (ProgressBar) dialog.findViewById(R.id.progress_horizontal);
    final TextView text2 = dialog.findViewById(R.id.value123);


    new Thread(new Runnable() {
        @Override
        public void run() {
            while (status < 100) {

                status += 1;

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        text.setProgress(status);
                        text2.setText(String.valueOf(status));

                        if (status == 100) {
                            dialog.dismiss();
                        }
                    }
                });
            }
        }
    }).start();


    dialog.show();

    Window window = dialog.getWindow();
    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}

布局文件:对话框

<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">

<ProgressBar
    android:id="@+id/progress_horizontal"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp" />

<RelativeLayout
    android:layout_width="wrap_content"
    android:paddingLeft="20dp"
    android:layout_margin="16dp"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/value123"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
      />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/value123"
        android:text="%" />
</RelativeLayout>

结果:

使用异步任务:

int status = 0;
Handler handler = new Handler();
Dialog dialog;
ProgressBar text;
TextView text2;

public void showDialog(Activity activity, String msg) {
    dialog = new Dialog(activity);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(false);
    dialog.setContentView(R.layout.dialog);

    text = (ProgressBar) dialog.findViewById(R.id.progress_horizontal);
    text2 = dialog.findViewById(R.id.value123);


    dialog.show();

    Window window = dialog.getWindow();
    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (status < 100) {

                status += 1;

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        text.setProgress(status);
                        text2.setText(String.valueOf(status));

                        if (status == 100) {
                            status = 0;
                        }
                    }
                });
            }
        }
    }).start();

}


private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {


        // it will fill the progress bar to 100
        // and will refill again and again



        /*
         *
         * Make your api call here
         * MAke request to API and return data when response comes
         *
         *
         * */

        /*
        * 
        * I have just add sleep to thead for example purposes
        * 
        * */
        try {
            Thread.sleep(30 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return resp;
    }


    @Override
    protected void onPostExecute(String result) {


        /*
         *
         *
         * Do your processing there on the api result
         *
         *
         * */
        dialog.dismiss();
    }


    @Override
    protected void onPreExecute() {
        showDialog(MainActivity.this,"");

    }


    @Override
    protected void onProgressUpdate(String... text) {

    }
}

启动异步任务:

    new AsyncTaskRunner().execute("fs");

我不确定这是否是最好的方法


2
投票

如果有人正在寻找带有百分比的圆形进度条,这里是 Kotlin 版本。

class PercentageProgressBar : ProgressBar {

    private lateinit var textPaint: Paint
    private lateinit var circlePaint: Paint
    private var currentProgress = 0

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        setWillNotDraw(false)

        circlePaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
        val whileColor = ContextCompat.getColor(context, android.R.color.white)
        circlePaint.color = whileColor

        textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
        val blackColor = ContextCompat.getColor(context, android.R.color.black)
        textPaint.color = blackColor
        textPaint.textSize = 20F
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val w = MeasureSpec.getSize(widthMeasureSpec)
        val h = MeasureSpec.getSize(heightMeasureSpec)
        val size = w.coerceAtMost(h)
        setMeasuredDimension(size, size)
    }

    private val r: Rect = Rect()

    override fun onDraw(canvas: Canvas) {

        val circleX = (width / 2).toFloat()
        val circleY = (height / 2).toFloat()
        val radius = (width / 2.5).toFloat()
        canvas.drawCircle(circleX, circleY, radius, circlePaint);

        // https://stackoverflow.com/a/32081250/7436566
        val textToPrint = "$currentProgress %"
        canvas.getClipBounds(r)
        val cHeight: Int = r.height()
        val cWidth: Int = r.width()
        textPaint.textAlign = Paint.Align.LEFT
        textPaint.getTextBounds(textToPrint, 0, textToPrint.length, r)
        val x: Float = cWidth / 2f - r.width() / 2f - r.left
        val y: Float = cHeight / 2f + r.height() / 2f - r.bottom
        canvas.drawText(textToPrint, x, y, textPaint)
        super.onDraw(canvas)
    }

    override fun setProgress(progress: Int) {
        super.setProgress(progress)
        
        // Hide when progress is 100
        if (progress == 100) {
            visibility = View.GONE
            return
        }
        currentProgress = progress
        invalidate()
    }
}

0
投票

我用的是这个方法

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">



    <ProgressBar
        android:id="@+id/dialog_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        style="?android:attr/progressBarStyleHorizontal"
        android:indeterminate="false"
        android:progress="0"
        />

    <TextView
        android:id="@+id/progress_percentage_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/dialog_progress_bar"
        android:layout_alignParentStart="true"
        android:text="0%"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/total_number_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/dialog_progress_bar"
        android:layout_alignParentEnd="true"
        android:text="0/0"
        android:textSize="16sp"/>

</RelativeLayout>
© www.soinside.com 2019 - 2024. All rights reserved.