Skip to content Skip to sidebar Skip to footer

Disabling All Child Views Inside The Layout

I saw many threads related to this, before posting my question. But none worked for me. I have a RelativeLayout with many other layouts and fragments as children. I want to disable

Solution 1:

Because your layouts are so heavily nested, you need to recursively disable the views. Instead of using your method, try something like this:

privatestaticvoiddisable(ViewGroup layout) {
    layout.setEnabled(false);
    for (inti=0; i < layout.getChildCount(); i++) {
        Viewchild= layout.getChildAt(i);
        if (child instanceof ViewGroup) {
            disable((ViewGroup) child);
        } else {
            child.setEnabled(false);
        }
    }
}

then call:

disable(content_view);

Solution 2:

Even though the answer is expected instead of using recursion I think the below code will do the trick.This is what I used to disbale it. I just passed parentlayout and whether to show or hide as a boolean parameter

privatevoiddisable(LinearLayout layout, boolean enable) {
        for (inti=0; i < layout.getChildCount(); i++) {
            Viewchild= layout.getChildAt(i);
            child.setEnabled(enable);
            if (child instanceof ViewGroup) {
                ViewGroupgroup= (ViewGroup) child;
                for (intj=0; j < group.getChildCount(); j++) {
                    group.getChildAt(j).setEnabled(enable);
                }
            }

        }

Solution 3:

Here are Kotlin versions:

Using Android KTX

fun View.changeEnableChildren(enable: Boolean) {
    isEnabled = enable
    (thisas? ViewGroup)?.let {
        forEach {
            changeEnableChildren(enable)
        }
    }
}

Without Android KTX

fun View.changeEnableChildren(enable: Boolean) {
    isEnabled = enable
    (thisas? ViewGroup)?.let {
        for (i in0..it.childCount) {
            changeEnableChildren(enable)
        }           
    }
}

Note: recursive method may cause StackOverFlowError in that case you should replace changeEnableChildren(enable) with isEnabled=enable

Solution 4:

apply android:duplicateParentState="true" to the children

Post a Comment for "Disabling All Child Views Inside The Layout"