Как показать ProgressBar в центре экрана независимо от типа макета - PullRequest
1 голос
/ 30 мая 2019

Интересно, есть ли какой-нибудь способ показать ProgressBar в центре экрана программно, независимо от типа макета текущей операции, например, тост можно показать как,

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

Ответы [ 4 ]

2 голосов
/ 30 мая 2019

Вот что я использую, я беру значок приложения и поворачиваю его в середине экрана, чтобы показать, как прогресс, это выглядит лучше, чем просто отображение индикатора выполнения. Если вы все еще хотите прогрессбар, просто замените 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
    }


}

Чтобы показать и скрыть Progress, я использую эти методы

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
}
0 голосов
/ 30 мая 2019

Спасибо 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()
}
0 голосов
/ 30 мая 2019

Поскольку 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;
    }
}
0 голосов
/ 30 мая 2019
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));
    }
...