ProgressDialog is deprecated.What is the alternate one to use?
Asked Answered
V

22

284

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 using android studio version 2.3.3.

ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.show();
Verisimilar answered 28/7, 2017 at 12:1 Comment(1)
Possible duplicate of ProgressDialog is deprecatedAnthelion
S
232

Yes, in API level 26 it's deprecated. Instead, you can use progressBar.

To create it programmatically:

First get a reference to the root layout

RelativeLayout layout = findViewById(R.id.display);  //specify here Root layout Id

or

RelativeLayout layout = findViewById(this);

Then add the progress bar

progressBar = new ProgressBar(youractivity.this, null, android.R.attr.progressBarStyleLarge);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(progressBar, params);

To show the progress bar

progressBar.setVisibility(View.VISIBLE);

To hide the progress bar

progressBar.setVisibility(View.GONE);

To disable the user interaction you just need to add the following code

getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                           WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

To get user interaction back you just need to add the following code

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

Just for future reference, change the android.R.attr.progressBarStyleSmall to android.R.attr.progressBarStyleHorizontal.

The code below only works above API level 21

progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));

To create it via xml:

<ProgressBar
        android:id="@+id/progressbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        android:max="100"
        android:backgroundTint="@color/white"
        android:layout_below="@+id/framelauout"
        android:indeterminateTint="#1a09d6"
        android:layout_marginTop="-7dp"/>

In your activity

progressBar = (ProgressBar) findViewById(R.id.progressbar);

Showing/hiding the progress bar is the same

 progressBar.setVisibility(View.VISIBLE); // To show the ProgressBar 
 progressBar.setVisibility(View.INVISIBLE); // To hide the ProgressBar

Here is a sample image of what it would look like:

Someplace answered 10/8, 2017 at 12:27 Comment(13)
It's like you been using this and you go like yeah finally progress dialog is deprecated, so I can show my potential to the world :D, just kidding, thanks so much for that detailed answer.Rumple
but how to setMessage() to it?Cecum
look at this ; #18411484Someplace
please update the xml code to "@android:color/white"Wreckage
To get horizontal Bar please use: ProgressBar progressBar = new ProgressBar(youractivity.this,null,android.R.attr.progressBarStyleHorizontal); progressBar.setIndeterminate(true);Berserker
Wow, this is actually not a good approach as of today, you shouln't block the UI, that's why this got deprecated! Oussema Aroua solution is better.Commutual
@Commutual Thing is, blocking the UI is exactly what I want to do, because I don't want the user to be able to interact with in until the background task is finished.Tilefish
@Ben Jaguar Marshall that's a REALLY bad app behavior and the last thing you should do, it's what all Google Devs and the documentation say.Commutual
@Commutual How is that bad app behaviour? The user should not be able to do anything before the app is ready; otherwise you'll get issues. Showing a "please wait" type dialog has been a pretty standard way of doing it for decades.Tilefish
@Ben Jaguar Marshall that's straight false, please read more and watch more Google videos, since at least 2014 they strongly discourage doing so! NEVER EVER block the UI, you must learn how to run operations in the background and react accordingly once they finished.Commutual
@Commutual So you're saying that Google advocates that users should be able to open empty dropdowns, see placeholder items and press buttons while the background thread is preparing the app's data? That's horrible design! A "please wait" dialog should be shown, preferably animated to show the app hasn't stalled, and then allow the user to interact with the UI once the app is prepared. If however you mean "don't do heavy stuff on the UI thread", then that makes sense. When I say "blocking the UI", I mean preventing interaction by the user, not doing work on the UI thread.Tilefish
So, now instead one line of code I need white dozens with about the same result? Great work google!Besides
There are problems with this solution "as is", particularly if you are using fragment navigation (single fragment apps). This does not disable backwards nav, so clicking said nav will result in the the previous screen being untouchable (and likely interrupting you async). It also will not survive a config change (say device re-orientation) regardless of whether you are using fragments or not.Strangulation
E
63

you can use AlertDialog as ProgressDialog refer below code for the ProgressDialog. This function you need to call whenever you show a progress dialog.

Code:

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

public class ProgressHelper {

    private static AlertDialog dialog = null;

    public static void showDialog(Context context, String message) {
        if(dialog == null){
            int llPadding = 30;
            LinearLayout ll = new LinearLayout(context);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            ll.setPadding(llPadding, llPadding, llPadding, llPadding);
            ll.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            llParam.gravity = Gravity.CENTER;
            ll.setLayoutParams(llParam);

            ProgressBar progressBar = new ProgressBar(context);
            progressBar.setIndeterminate(true);
            progressBar.setPadding(0, 0, llPadding, 0);
            progressBar.setLayoutParams(llParam);

            llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            llParam.gravity = Gravity.CENTER;
            TextView tvText = new TextView(context);
            tvText.setText(message);
            tvText.setTextColor(Color.parseColor("#000000"));
            tvText.setTextSize(20);
            tvText.setLayoutParams(llParam);

            ll.addView(progressBar);
            ll.addView(tvText);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setCancelable(true);
            builder.setView(ll);

            dialog = builder.create();
            dialog.show();
            Window window = dialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                layoutParams.copyFrom(dialog.getWindow().getAttributes());
                layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
                layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                dialog.getWindow().setAttributes(layoutParams);
            }
        }
    }

    public static  boolean isDialogVisible(){
        if(dialog != null){
            return dialog.isShowing();
        }else {
            return false;
        }
    }

    public static  void dismissDialog(){
        if(dialog != null){
            dialog.dismiss();
            dialog = null;
        }
    }
}

Output:

enter image description here

Endogenous answered 14/3, 2018 at 8:21 Comment(9)
How to dismiss it?Emmalynne
make one base class like BaseActivity then after adding this piece of code, also add one method dismiss dialog but for that, you need to define 'AlertDialog dialog' object globallyEndogenous
then simply call dialog.dismiss() method inside your hide dialog method.Endogenous
Everything is fine but on tapping anywhere on screen dialog getting dismissed.Service calls in progress and suer is able to dismiss it and play with the ui which is not good right.Any Solution ?Gooch
You can set it not cancellable, but rotating the device or use split screen it would be dismissed anyway and the user can interact with the UI which is not ready. Maybe AlertDialog should not be used here.Mosquito
Best way to show "Loading" dialog without additional XML layout, thanks!Asberry
I am unable to dismiss it. I am calling it at onClick of a button.Willowwillowy
@FaisalQayyum makes AlertDialog dialog instance global and used for dismissing.Endogenous
@KishanDonga AlertDialog dialog = new AlertDialog(); it is giving me cannot reslove constructor AlterDialog()Willowwillowy
S
39

You can simply design an xml interface for your progressbar and pass it as a view to a AlertDialog, then show or dismiss the dialog anytime you want.

progress.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="13dp"
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ProgressBar
        android:id="@+id/loader"
        android:layout_marginEnd="5dp"
        android:layout_width="45dp"
        android:layout_height="45dp" />
    <TextView
        android:layout_width="wrap_content"
        android:text="Loading..."
        android:textAppearance="?android:textAppearanceSmall"
        android:layout_gravity="center_vertical"
        android:id="@+id/loading_msg"
        android:layout_toEndOf="@+id/loader"
        android:layout_height="wrap_content" />

</LinearLayout>

The code code that displays the progress dialog. Just copy this code and paste it your fragment.

Dialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(R.layout.progress);
        // This should be called once in your Fragment's onViewCreated() or in Activity onCreate() method to avoid dialog duplicates.
        dialog = builder.create();
    }
    
//   This method is used to control the progress dialog.
      private void setDialog(boolean show){
               if (show)dialog.show();
                    else dialog.dismiss();
           }

Then just call the method whenever you want to show the progressdialog and pass true as an argument to show it or false to dismiss the dialog.

Sparker answered 9/10, 2017 at 5:3 Comment(6)
@Alok Rajasukumaran it seems you're using activity, simply replace it with this , so that it look like this AlertDialog.Builder builder = new AlertDialog.Builder(this); .Please make sure you're copying the right code.Sparker
layout_toEndOf can be removed since not for LinearLayoutAnthropophagy
I have been trying to show progress bar via alter dialog but i am having some issues can you please check my question?Willowwillowy
when I call setDialog(false), the dialog won't disappear. Only if I touch the screen it wii be goneHakon
I know it's way too late to help @Darksymphony, but setDialog should not be calling builder.create(). That should only happen once, or a second dialog will be created when the calling code wants to dismiss() the first. Thus, the first one is still shown...Spadix
@CarlSmith You're right. I provided the code snippet as an example of how the progress dialog can be achieved.Sparker
M
33

Yes, ProgressDialog is deprecated but Dialog isn't.

You can inflate your own XML file ( containing a progress bar and a loading text) into your dialog object and then display or hide it using the show() and dismiss() functions. Here is an example (Kotlin):

ProgressDialog class:

class ProgressDialog {
companion object {
    fun progressDialog(context: Context): Dialog{
        val dialog = Dialog(context)
        val inflate = LayoutInflater.from(context).inflate(R.layout.progress_dialog, null)
        dialog.setContentView(inflate)
        dialog.setCancelable(false)
        dialog.window!!.setBackgroundDrawable(
                ColorDrawable(Color.TRANSPARENT))
        return dialog
    }
  }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:background="#fff"
android:padding="13dp"
android:layout_height="wrap_content">
<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyle"
    android:layout_width="100dp"
    android:layout_margin="7dp"
    android:layout_height="100dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_margin="7dp"
    android:layout_toEndOf="@+id/progressBar"
    android:text="Loading..." />
</RelativeLayout>

In your code: Just do var dialog = ProgressDialog.progressDialog(context)

To show: dialog.show()

To hide: dialog.dismiss()

Musser answered 30/3, 2018 at 11:48 Comment(1)
Great solution! Just posted an alternative version of the ProgressDialog class below.Dupre
D
32

ProgressBar is very simple and easy to use, i am intending to make this same as simple progress dialog. first step is that you can make xml layout of the dialog that you want to show, let say we name this layout

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="horizontal"
    android:padding="20dp">
    <ProgressBar
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="4"
        android:gravity="center"
        android:text="Please wait! This may take a moment." />
</LinearLayout>

next step is create AlertDialog which will show this layout with ProgressBar

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false); // if you want user to wait for some process to finish,
builder.setView(R.layout.layout_loading_dialog);
AlertDialog dialog = builder.create();

now all that is left is to show and hide this dialog in our click events like this

dialog.show(); // to show this dialog
dialog.dismiss(); // to hide this dialog

and thats it, it should work, as you can see it is farely simple and easy to implement ProgressBar instead of ProgressDialog. now you can show/dismiss this dialog box in either Handler or ASyncTask, its up to your need

Dorice answered 5/8, 2018 at 12:43 Comment(4)
Please, change progress_dialog.show(); to builder.show();. Thank you.Tabasco
I have changed the name to right AlertDialog object on, show() / dismiss(), but I didn't put builder.show() because then to dismiss it we would have to do dialog.dismiss() which is kind of confusing for someone who likes to keep their code simple and easy to understand, and also because builder.show() returns AlertDialog object, and we will have to save that reference like AlertDialog dialog = builder.show(); then do dialog.dismiss(), its easier to have builder.create() return in some AlertDialog object, and then use that object to show and hide the dialogDorice
We may use "runOnUiThread(new Runnable() { @Override public void run() { dialog.show/dismiss(); } });", if the calling thread is not Main UI Thread. ( useful when we use to call from WebView - shouldoverride methods. )Mongeau
I have been trying to show progress bar via alter dialog but i am having some issues can you please check my question?Willowwillowy
S
31

This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. link

It's deprecated at Android O because of Google new UI standard

Slim answered 28/7, 2017 at 12:8 Comment(9)
"This class was deprecated in API level 26" is used instead of a date. They don't want you to use it anymore. Yes, it is because of new UI standards, but they apply for every API level...Counterfactual
"It's deprecated at Android O because of Google new UI standard" - link please new UI standardTake
And the reason for deprecating it is because it blocks user input? Sometimes I wonder what kind of powder Google engineers are snorting. It's much easier to use a blocking dialog than having to hide/disable input controls and then enable a progressbar. Foolish thinking on Google's part.Faun
@Faun The Android UI is designed around making the user feel a false sense of freedom at the cost of expensive workarounds to prevent fatal errors that result from it. Wait until you get into permissions and what the carriers have paid Google to say you can and can't access.Letter
I guess they're more interested in preventing abuse of modal dialogs: sometimes they are shown to make the user wait for the end of an operation in circumstances in which the user shouldn't need to wait at all, but could continue doing other things, so making them wait unnecessarily degrades the user experience. Notwithstanding, there are plenty of circumstances in which there's no choice for the user but wait for an operation to complete, so I agree that there should be a non-deprecated standard method for these cases instead of forcing each developer implementing their own.Pelops
I have been trying to show progress bar via alter dialog but i am having some issues can you please check my question?Willowwillowy
@Faun I hope after 2 years you learned more, "It's much easier to use a blocking dialog" who cares what's easier for the developer, the user is the king and the app should behave in the best way FOR THE USER.Commutual
@Commutual Look at the upvotes on my comment. Tell those people too. I think the decision by Google was more political. And I'm still using dialog boxes. So, jokes on you and Google.Faun
The hubris of the Android team unilaterally deciding they know what my customers need better than I do is simply incredible. Blocking interaction with the UI is a very common need and used to be served perfectly by ProgressDialog. Now I have to waste yet another chunk of my life reinventing the wheel AGAIN.Elaboration
G
17

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:

enter image description here

Ghostwrite answered 1/9, 2019 at 6:36 Comment(2)
how to use in fragment? what is context in fragment?Feodore
Usually in your fragment you can get your current view, so the context should be: view!!.contextGhostwrite
S
13

Well if you really wants to go against their will, still you can use Sweet Alert Dialog or create one on your own.

progress_dialog_layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableRow
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="64dp" >

        <ProgressBar
            android:id="@+id/progressBar2"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:gravity="center|left"
            android:id="@+id/textView9"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:text="Downloading data. Please wait.." />
    </TableRow>
</RelativeLayout>

Java code:

AlertDialog b;
AlertDialog.Builder dialogBuilder;

public void ShowProgressDialog() {
dialogBuilder = new AlertDialog.Builder(DataDownloadActivity.this);
LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
            View dialogView = inflater.inflate(R.layout.progress_dialog_layout, null);
            dialogBuilder.setView(dialogView);
            dialogBuilder.setCancelable(false);
            b = dialogBuilder.create();
            b.show();
        }

        public void HideProgressDialog(){

            b.dismiss();
        }
Stockholm answered 16/8, 2017 at 4:29 Comment(4)
I have had terrible experiences with SweetAlertDialog in a production setting, be very cautious as it leaks from window to window.Hyetal
for me HideProgress does nothing.Foreandaft
Why to use a library just to show a progress dialog?Wenwenceslaus
a note, here TableRow it's the same as using a horizontal LinearLayout given that the parent is not a TableLayout developer.android.com/reference/android/widget/TableRowBay
G
7

ProgressBar is best alternative for ProgressDialog. A user interface element that indicates the progress of an operation.

For more info see this Google doc: https://developer.android.com/reference/android/widget/ProgressBar.html

Grandeur answered 28/7, 2017 at 12:5 Comment(1)
He said "apart from progressbar".Counterfactual
C
5

As mentioned on the documentation page the alternative is ProgressBar. ProgressDialog's look can be replicated by placing a ProgressBar into an AlertDialog.

You can still use it, but Android does not want you to use it, that is why it is deprecated. So you should consider solving your problem in another way, like embedding a ProgressBar into your Layout.

Counterfactual answered 28/7, 2017 at 12:6 Comment(1)
@PeterHaddad It works "normally" in api 28 in my project and the same as in lower apis. As the deprecation suggests, it is no longer supported and may not work in the future.Depressor
S
4

ProgressDialog was deprecated in API level 26 .

"Deprecated" refers to functions or elements that are in the process of being replaced by newer ones.

ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI.

Advantage

I would personally say that ProgressBar has the edge over the two .ProgressBar is a user interface element that indicates the progress of an operation. Display progress bars to a user in a non-interruptive way. Show the progress bar in your app's user interface.

Slocum answered 5/10, 2017 at 15:29 Comment(0)
W
2

Maybe this guide could help you.

Usually I prefer to make custom AlertDialogs with indicators. It solves such problems like customization of the App view.

Wallet answered 28/7, 2017 at 12:9 Comment(0)
C
2

It may help to other people.

Lots of popular apps have the different approach to show the progress of anything like network request, file loading etc. Loading spinner doesn't show the how much content has been loaded or remaining to load. There is a period of uncertainty which is bad in the perspective of UI/UX. Lot of popular apps(Facebook, Linkedin etc) has resolved this issue by showing the bare bones UI displays first. Then the loaded content is gradually populated on-screen.

I have used the shimmer for my apps to solve this issue.

There is a good article about this which will be beneficial for other people

Contractile answered 24/8, 2017 at 18:22 Comment(0)
C
2

I use DelayedProgressDialog from https://github.com/Q115/DelayedProgressDialog It does the same as ProgressDialog with the added benefit of a delay if necessary.

Using it is similar to ProgressDialog before Android O:

DelayedProgressDialog progressDialog = new DelayedProgressDialog();
progressDialog.show(getSupportFragmentManager(), "tag");
Checkmate answered 16/9, 2017 at 2:2 Comment(0)
T
2

You can use this class I wrote. It offers only the basic functions. If you want a fully functional ProgressDialog, then use this lightweight library.

Gradle Setup

Add the following dependency to module/build.gradle:

compile 'com.lmntrx.android.library.livin.missme:missme:0.1.5'

How to use it?

Usage is similar to original ProgressDialog

ProgressDialog progressDialog = new 
progressDialog(YourActivity.this);
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.dismiss();

NB: You must override activity's onBackPressed()

Java8 Implementation:

@Override
public void onBackPressed() {
    progressDialog.onBackPressed(
            () -> {
                super.onBackPressed();
                return null;
            }
    );
}

Kotlin Implementation:

override fun onBackPressed() {
   progressDialog.onBackPressed { super.onBackPressed() }
}
  • Refer Sample App for the full implementation
  • Full documentation can be found here
Tensible answered 14/3, 2018 at 15:29 Comment(0)
D
2

Here is my kotlin version of the ProgressDialog class suggested by @Han

class ProgressDialog(context: Context) : Dialog(context) {
init {
    val view = View.inflate(context, R.layout.progress_dialog, null)
    setContentView(view)
    setCancelable(false)
    window?.setBackgroundDrawable(
        ColorDrawable(Color.TRANSPARENT)
    )
}

}

Dupre answered 2/7, 2021 at 22:9 Comment(0)
S
2

Another solution with Kotlin and androidx DialogFragment

By using DialogFragment you don't have to resize the window every time and on every screen where you need to show the dialog, I think this is a cleaner solution

  1. Create dialog class

class BaseProgressDialog : DialogFragment() {

    companion object {
        const val DIALOG_TAG = "BaseProgressDialogFragment"
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(it, R.style.MainAlertDialog)
            val inflater = requireActivity().layoutInflater
            val dialogView = inflater.inflate(R.layout.progress_dialog, null)

            builder.setView(dialogView)
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.setCanceledOnTouchOutside(false)
        dialog?.setCancelable(false)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        val size = resources.getDimensionPixelSize(R.dimen.size_80dp)
        dialog?.window?.setLayout(size, size)
    }
}
  1. Create style in your styles.xml
<style name="MainAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowBackground">@drawable/bg_alert_dialog</item>
</style>
  1. Create background for your dialog bg_alert_dialog.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="?attr/colorSecondary"/>
    <corners android:radius="@dimen/radius_10dp" />
</shape>
  1. Create layout for dialog progress_dialog.xml
    <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="match_parent"
    android:background="@drawable/bg_alert_dialog"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="@dimen/padding_16dp">

    <com.google.android.material.progressindicator.CircularProgressIndicator
        android:layout_width="@dimen/size_40dp"
        android:layout_height="@dimen/size_40dp"
        android:indeterminate="true"
        app:indicatorColor="?attr/colorPrimary" />

</LinearLayout>
  1. Call dialog in the Fragment
private var progressDialog = BaseProgressDialog()
activity?.let {
   progressDialog.show(it.supportFragmentManager, BaseProgressDialog.DIALOG_TAG)
}

And this is what it will look like:

enter image description here

Sequela answered 1/12, 2022 at 10:30 Comment(0)
G
1

Use this simple trick

//initialize

val dialog : Dialog = Dialog(this)

//set layout

dialog.setContentView(R.layout.view_loading)

//show dialog

dialog.show()

// remove white background

dialog.window.setbackgroundDrawable(ColorDrawable(0))
Gmt answered 26/6, 2021 at 14:34 Comment(0)
B
0

In the progress dialog, user cannot do any kind of work. All the background processes are stopped during progress dialog. So, It is advisable to user progress-bar instead of progress dialog.

Bioastronautics answered 16/6, 2019 at 8:13 Comment(0)
P
0

Here my version for an indeterminate progress 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:padding="20dp">

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="4"
        android:gravity="center"
        android:textAlignment="textStart"
        android:id="@+id/message"
        tools:text="Please wait..." />
</LinearLayout>

IndeterminateProgressDialog.kt:

class IndeterminateProgressDialog(context: Context) : AlertDialog(context) {
    private val messageTextView: TextView

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_loading_dialog, null)
        messageTextView = view.findViewById(R.id.message)
        setView(view)
    }

    override fun setMessage(message: CharSequence?) {
        this.messageTextView.text = message.toString()
    }

}

Usage:

   val dialog = IndeterminateProgressDialog(context)
                    dialog.setMessage("Please wait...")
                    dialog.setCanceledOnTouchOutside(false)
                    dialog.setCancelable(false)
                    dialog.show()
Posting answered 17/3, 2021 at 17:19 Comment(0)
L
0

create a xml file with progress-bar and other view and inflate your derived Dialog class view with this xml file or Alertdialog derived class. Which have been provided in other solution with detailed. But if you want a go to solution or existed lib. i found these two.

  1. https://github.com/Livin21/MissMe

  2. https://github.com/skydoves/ProgressView

These are just perfect and two the point as per need.

Limn answered 1/6, 2022 at 19:33 Comment(0)
A
-1

You can use SpotDialog by using the library wasabeef you can find the complete tutorial from the following link:

SpotsDialog Example in Android

Alvera answered 12/1, 2018 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.