Get the View of the fragment, and disable the whole view

12,805

Solution 1

As per @Georgy's comment, here is a copy of the answer from Disable the touch events for all the views (credit to @peceps).


Here is a function for disabling all child views of some view group:

 /**
   * Enables/Disables all child views in a view group.
   * 
   * @param viewGroup the view group
   * @param enabled <code>true</code> to enable, <code>false</code> to disable
   * the views.
   */
  public static void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
    int childCount = viewGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
      View view = viewGroup.getChildAt(i);
      view.setEnabled(enabled);
      if (view instanceof ViewGroup) {
        enableDisableViewGroup((ViewGroup) view, enabled);
      }
    }
  }

You can call this passing in your Fragment's view as retrieved by Fragment.getView(). Assuming that your fragment's view is a ViewGroup.

Solution 2

Here's a Kotlin implementation with @Marcel's suggestion.

fun ViewGroup.enableDisableViewGroup(enabled: Boolean, affectedViews: MutableList<View>) {
    for (i in 0 until childCount) {
        val view = getChildAt(i)
        if (view.isEnabled != enabled) {
            view.isEnabled = enabled
            affectedViews.add(view)
        }

        (view as? ViewGroup)?.enableDisableViewGroup(enabled, affectedViews)
    }
}

fun MutableList<View>.restoreStateAndClear(enabled: Boolean) {
    forEach { view -> view.isEnabled = enabled }
    clear()
}
Share:
12,805
Leem.fin
Author by

Leem.fin

A newbie in software development.

Updated on June 05, 2022

Comments

  • Leem.fin
    Leem.fin almost 2 years

    In my main.xml layout, I have an <FrameLayout> element which is the fragment placeholder:

    main.xml:

    <FrameLayout
            android:id="@+id/fragment_placeholder"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
    

    I add Fragment programmatically to the above <FrameLayout> by:

    fragmentTransaction.add(R.id.fragment_placeholder, fragment, null);
    

    I can then use the replace() to change to other fragment:

    fragmentTransaction.replace(R.id.fragment_placeholder, otherFragment, null);
    

    At some point of my project, I need to get the current showing fragment, and disable everything on the view. I firstly successfully get the current showing fragment by :

    Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_placeholder); 
    

    Then, how can I disable the view of the fragment ? On the view, there could be buttons, is it possible to disable the whole view? If it is not possible, how can I add an overlay on the view?

    I tried:

    currentFragment.getView().setEnabled(false); 
    

    But, it does not work, I can still click on buttons on the view.