ProgressDialog is deprecated.What is the alternate one to use?

后端 未结 17 980
面向向阳花
面向向阳花 2020-11-27 09:11

I have come across to see that ProgressDialog is now deprecated. What would be alternate one to use in place of that apart from ProgressBar. I am

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 10:00

    You don't need to import any custom library.

    I prefer to use the modern AlertDialog so this is the Kotlin version for the great answer posted by Kishan Donga in this page.

    Kotlin code:

    fun setProgressDialog(context:Context, message:String):AlertDialog {
        val llPadding = 30
        val ll = LinearLayout(context)
        ll.orientation = LinearLayout.HORIZONTAL
        ll.setPadding(llPadding, llPadding, llPadding, llPadding)
        ll.gravity = Gravity.CENTER
        var llParam = LinearLayout.LayoutParams(
                      LinearLayout.LayoutParams.WRAP_CONTENT,
                      LinearLayout.LayoutParams.WRAP_CONTENT)
        llParam.gravity = Gravity.CENTER
        ll.layoutParams = llParam
    
        val progressBar = ProgressBar(context)
        progressBar.isIndeterminate = true
        progressBar.setPadding(0, 0, llPadding, 0)
        progressBar.layoutParams = llParam
    
        llParam = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT)
        llParam.gravity = Gravity.CENTER
        val tvText = TextView(context)
        tvText.text = message
        tvText.setTextColor(Color.parseColor("#000000"))
        tvText.textSize = 20.toFloat()
        tvText.layoutParams = llParam
    
        ll.addView(progressBar)
        ll.addView(tvText)
    
        val builder = AlertDialog.Builder(context)
        builder.setCancelable(true)
        builder.setView(ll)
    
        val dialog = builder.create()
        val window = dialog.window
        if (window != null) {
            val layoutParams = WindowManager.LayoutParams()
            layoutParams.copyFrom(dialog.window?.attributes)
            layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
            layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
                    dialog.window?.attributes = layoutParams
        }
        return dialog
    }
    

    Usage:

    val dialog = setProgressDialog(this, "Loading..")
    dialog.show()
    

    Output:

提交回复
热议问题