无论布局类型如何,如何在屏幕中央显示 ProgressBar

How to show ProgressBar in centre of screen regardless layout types

我想知道是否有任何方法可以通过编程方式在屏幕中间显示一个 ProgressBar,而不管当前 Activity 的布局类型如何,就像吐司一样可以显示,

Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
public static void showProgressDialog(Context context) {
    if (mDialog != null && mDialog.isShowing()) {
        mDialog.dismiss();
        mDialog = null;
    }

    try {
        mDialog = new ProgressDialog(context, R.style.MyAlertDialogStyle);
        mDialog.show();
        mDialog.setCancelable(false);
        if (mDialog.getWindow() != null)
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        mDialog.setContentView(R.layout.progress_layout);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();

        layoutParams.copyFrom(mDialog.getWindow().getAttributes());

        int dialogWindowWidth = Validator.DtP(200,context);
        int dialogWindowHeight = Validator.DtP(150,context);

        layoutParams.width = dialogWindowWidth;
        layoutParams.height = dialogWindowHeight;

        // Apply the newly created layout parameters to the alert dialog window
        mDialog.getWindow().setAttributes(layoutParams);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // dialog.setMessage(Message);

}

public static void hideProgressDialog(Context context) {
    ((Activity)context).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
        }
    });

}

 public static int DtP(float dp, Context context) {
        return (int) (dp * (context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT));
    }

由于 ProgressDialog 已弃用,您可以使用对话框(默认情况下出现在屏幕中央)在中央显示进度条。

layout_loading_progress_bar.xml :

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

<ProgressBar
    android:id="@+id/progress_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@id/progress_text"
    android:layout_margin="@dimen/dimen_10dp"
    android:theme="@style/AppTheme.WhiteAccent" />

<TextView
    android:id="@+id/progress_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="@dimen/dimen_10dp"
    android:text="Loading..."
    android:textColor="@color/textYellow"
    android:textSize="17sp" />

LoadingProgressBar.java

public void showProgress(Context context, String message, boolean cancelable) {
    mDialog = new Dialog(context);
    mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mDialog.setContentView(R.layout.layout_loading_progress_bar);
    WindowManager.LayoutParams params = mDialog.getWindow().getAttributes();
    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    mDialog.getWindow().setAttributes(params);
    ProgressBar mProgressBar = mDialog.findViewById(R.id.progress_bar);
    TextView progressText = mDialog.findViewById(R.id.progress_text);
    progressText.setText(message);
    progressText.setVisibility(View.VISIBLE);
    mProgressBar.setVisibility(View.VISIBLE);
    mProgressBar.setIndeterminate(true);
    mDialog.setCancelable(cancelable);
    mDialog.setCanceledOnTouchOutside(cancelable);
    mDialog.show();
}

public void hideProgress() {
    if (mDialog != null) {
        mDialog.dismiss();
        mDialog = null;
    }
}

这是我使用的,我将应用程序图标旋转到屏幕中间以显示进度,它看起来比只显示进度条更好。如果您仍然想要进度条,只需将 ImageView 替换为 ProgressBar

import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView

class MyProgressDialog : Dialog {
    private var dialog: Dialog? = null
    var imageView: ImageView? = null
        internal set
    internal var textView: TextView? = null


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

    constructor(context: Context, themeResId: Int) : super(context, themeResId) {
        init(context)
    }

    protected constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener) {
        init(context)
    }


    fun init(context: Context) {

        dialog = this

        dialog!!.window!!.requestFeature(Window.FEATURE_NO_TITLE)
        dialog!!.setCancelable(false)


        val relativeLayout = RelativeLayout(context)
        val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        relativeLayout.layoutParams = layoutParams


        val layoutParams_for_linear = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams_for_linear.addRule(RelativeLayout.CENTER_IN_PARENT)
        val linearLayout = LinearLayout(context)
        linearLayout.layoutParams = layoutParams_for_linear
        linearLayout.orientation = LinearLayout.VERTICAL

        relativeLayout.addView(linearLayout)


        val layoutParams_Linear = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        layoutParams_Linear.gravity = Gravity.CENTER


        imageView = ImageView(context)
        imageView!!.setImageResource(R.mipmap.ic_launcher)
        imageView!!.layoutParams = layoutParams_Linear

        linearLayout.addView(imageView)

        textView = TextView(context)
        textView!!.layoutParams = layoutParams_for_linear
        textView!!.setTextColor(Color.parseColor("#ffffff"))
        textView!!.textSize = 18f
        linearLayout.addView(textView)


        val animation = ObjectAnimator.ofFloat(imageView, "rotationY", 0.0f, 360f)
        animation.duration = 2500
        animation.repeatCount = ObjectAnimator.INFINITE
        animation.interpolator = AccelerateDecelerateInterpolator()
        animation.start()


        dialog!!.window!!.setContentView(relativeLayout, layoutParams)
        dialog!!.window!!.setBackgroundDrawable(
                ColorDrawable(android.graphics.Color.TRANSPARENT))


    }


    fun setProgressMessage(message: String): Dialog {

        if (textView != null)
            textView!!.text = message

        return this
    }

    fun setProgressMessageSize(size: Int): Dialog {

        if (textView != null)
            textView!!.textSize = size.toFloat()

        return this
    }

    fun setProgressMessageColour(colour: Int): Dialog {

        if (textView != null)
            textView!!.setTextColor(colour)

        return this
    }

    fun setIcon(resId: Int): Dialog {

        if (imageView != null) {
            imageView!!.setImageResource(resId)

        }

        return this
    }


}

为了显示和隐藏进度,我使用了这些方法

private var dialog: Dialog? = null

fun showProgress(context: Context?): Dialog? {
    if (context is Activity && (dialog == null || !dialog!!.isShowing)) {
        try {
            dialog = MyProgressDialog(context)
            dialog?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    return dialog
}

fun dismissProgress() {
    try {
        if (dialog != null && dialog!!.isShowing) {
            dialog?.dismiss()
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    dialog = null
}

感谢 ADM 和 Reddy 的指导。最后我能够使用对话框显示进度条,

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()
}