androidandroid-layoutandroid-widget

Disable all elements in a layout - Android


In my Android app there is a requirement that a number of UI elements should be disabled until a button is clicked. Can I disable all the UI elements in a layout by referring the layout without disable them one by one?


Solution

  • You could disable all views recursively like this. Just pass the layout as view to the method:

    private void enableViews(View v, boolean enabled) {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0;i<vg.getChildCount();i++) {
                enableViews(vg.getChildAt(i), enabled);
            }
        } 
        v.setEnabled(enabled);
    }
    

    Just run enableViews(view, false) to disable, or enableViews(view, true) to enable again.