I'm having trouble understanding how the visibility of a ProgressBar works. Basically my ProgressBar won't appear or disappear when I need it to. My code is too big to show all here so I have created a new simple demo project with a button to click:
fab.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
mProgressBar.setVisibility(View.VISIBLE);
SystemClock.sleep(1000);
mProgressBar.setVisibility(View.GONE);
SystemClock.sleep(1000);
mProgressBar.setVisibility(View.VISIBLE);
SystemClock.sleep(1000);
mProgressBar.setVisibility(View.GONE);
SystemClock.sleep(1000);
mProgressBar.setVisibility(View.VISIBLE);
}
}
mProgressBar = findViewById(R.id.progressbar);
mProgressBar.setVisibility(View.INVISIBLE);
I have also tried several versions of the Progressbar; currently it's this:
<ProgressBar
android:id="@+id/progressbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:backgroundTint="@android:color/white"
android:gravity="center"
android:indeterminate="true"
android:indeterminateTint="#1a09d6"/>
So, what happens is that the ProgressBar doesn't turn on and off; it just ends up with whatever is the last state. And the SnackBar doesn't appear either, until after all of the sleeps. If I could understand how to make this snippet work as I want, then I think would have a solution to the (slightly more complex) situation in my actual code. I have read other threads and understand that a ProgressBar can't be shown or updated while the main thread is too busy. I have tried, as others have suggested, using
runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressBar.setVisibility(View.GONE);
}
})
but this makes no difference. I have also tried View.Invalidate() between the visibility changes, but to no effect. And I've tried 'INVISIBLE' instead of 'GONE'. Clearly I'm missing something fundamental about tasks and threading here! Help please.