mercutio
mercutio

Reputation: 1066

Disable all UI-Elements while working in the background

Is there a method in the Android SDK that allows me to disable all UI-Elements such as Buttons and MenuItems while I perform a task in the background?

I currently do some work over the internet and display a ProgressBar informing the user about the current progress.

Should I just build a List<> of all my Buttons and MenuItems and update their state at the start and end of the background task via the setEnabled method?

Upvotes: 0

Views: 1651

Answers (1)

user
user

Reputation: 87064

Is there a method in the Android SDK that allows me to disable all UI-Elements such as Buttons and MenuItems while I perform a task in the background?

I don't recall of such a method being present in the SDK.

Should I just build a List<> of all my Buttons and MenuItems and update their state at the start and end of the background task via the setEnabled method?

My advice is to use a ProgressDialog instead of your current approach(the dialog will also prevent the users from interacting with the UI, you'll just have to disable the menu). If you start the background worker and disable all the UI views the user will see that there is some work being done and also that he/she can't use the app. For me this seems confusing and a Dialog seems a much better solution as it clearly indicates that the user must wait until the work is done. Another option is to place the ProgressBar in a overlay that will cover the activity so the user can still see the below UI if this is what you want.

To disable all the views I would use a method like the one below:

private void changeViewsState(ViewGroup parent, boolean state) {
    int count = parent.getChildCount();
    for (int i = 0; i < count; i++) {
        View child = parent.getChildAt(i);
        if (child instanceof ViewGroup) {
            changeViewsState((ViewGroup) child, state);
        } else if (child instanceof View) {
            child.setEnabled(state);
        }
    }
}

passing the system's content panel (changeViewsState((ViewGroup) findViewById(android.R.id.content), false);) or the root of your activity's layout:

ViewGroup root; // root is a reference of the root of your content view
// in the onCreate method

root = (ViewGroup) getLayoutInflater().inflate(R.layout.your_activity_layout_file, null);

// later use it:
changeViewsState(root, false);

To disable the menu items have a boolean flag that is set when the background work is about to begin and use that flag to enable/disable menu items in the callback onPrepareOptionMenu. When the work finishes remember to revert the flag so the menu will be enabled.

Upvotes: 2

Related Questions