For example I have:
If you're interested in disabling views in a specific ViewGroup then you can use the interesting, perhaps slightly obscure duplicateParentState
. A view state is a set of boolean attributes such as pressed, enabled, activated, and others. Just use this on each child you want to sync to parent ViewGroup:
android:duplicateParentState="true"
Note that it duplicates the entire state and not just the enabled state. This may be what you want! Of course, this approach is best if you're loading layout XML.
If some desperate developer scrolls down here, I have another option to do it. Which also disables scrolling as far as I experimented with it. The idea is to use View element like this one in a RelativeLayout, under all your UI elements.
<View
android:id="@+id/shade"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primaryShadow"
android:visibility="gone"/>
So it is set to be "gone" before some condition. And then you set it's visibility to VISIBLE when you want to disable your UI. Also you have to implement OnClickListener
for this View. This onClickListener
will catch click event and won't pass it to the underlying elements.
In Kotlin, you can use isDuplicateParentStateEnabled = true
before the View
is added to the ViewGroup
.
As documented in the setDuplicateParentStateEnabled
method, if the child view has additional states (like checked state for a checkbox), these won't be affected by the parent.
The xml analogue is android:duplicateParentState="true"
.
This is a pretty delayed answer.But it might help someone. Many answers mentioned above seem to be good. But if your layout.xml has nested viewgroups. Then above answers may not provide full result. Hence i have posted my opinion as a snippet. With the code below one can disable all views (Including Nested ViewGroups).
NOTE: Try avoiding nested ViewGroups as they are not recommended.
private void setEnableView(boolean b) {
LinearLayout layout = (LinearLayout)findViewById(R.id.parent_container);
ArrayList<ViewGroup> arrVg = new ArrayList<>();
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
if (child instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) child;
arrVg.add(vg);
}
child.setEnabled(b);
}
for (int j=0;j< arrVg.size();j++){
ViewGroup vg = arrVg.get(j);
for (int k = 0; k < vg.getChildCount(); k++) {
vg.getChildAt(k).setEnabled(b);
}
}
}
Set
android:descendantFocusability="blocksDescendants"
for yor ViewGroup view. All descendants will not take focus.