Search code examples
androidandroid-activitykotlinlayoutandroid-progressbar

How to show ProgressBar in centre of screen regardless layout types


I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

Solution

  • Thanks ADM and Reddy for guidance. Finally I was able to show a progressBar using dialog,

    var loadingDialog: Dialog? = null
    
    fun showLoadingDialog() {
    
        loadingDialog = Dialog(this)
    
        loadingDialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
        loadingDialog?.setCancelable(true)
    
        val relativeLayout = RelativeLayout(this)
        relativeLayout.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
    
        val progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleLarge)
        val params = RelativeLayout.LayoutParams(150, 150)
        params.addRule(RelativeLayout.CENTER_IN_PARENT)
    
        relativeLayout.addView(progressBar, params)
    
        loadingDialog?.window?.setContentView(relativeLayout, relativeLayout.layoutParams)
            loadingDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            loadingDialog?.show()
    }
    
    fun hideLoadingDialog(){
    
        loadingDialog?.hide()
    }