【问题标题】:Get the View of the fragment, and disable the whole view获取片段的视图,并禁用整个视图
【发布时间】:2012-07-31 07:15:48
【问题描述】:

在我的 ma​​in.xml 布局中,我有一个 <FrameLayout> 元素,它是 fragment 占位符

ma​​in.xml:

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

我将片段以编程方式添加到上述&lt;FrameLayout&gt; by:

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

然后我可以使用replace() 更改为其他片段:

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

在我的项目的某个时刻,我需要获取当前显示的片段,并禁用视图上的所有内容。我首先通过以下方式成功获取了当前显示的片段:

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

那么,如何禁用片段的视图? 视图上可能有按钮,是否可以禁用整个视图?如果不可能,如何在视图上添加叠加层?

我试过了:

currentFragment.getView().setEnabled(false); 

但是,它不起作用,我仍然可以单击视图上的按钮。

【问题讨论】:

标签: android android-layout android-intent android-emulator android-fragments


【解决方案1】:

这是一个带有 @Marcel 建议的 Kotlin 实现。

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()
}

【讨论】:

    【解决方案2】:

    根据@Georgy 的评论,这里是Disable the touch events for all the views 的答案副本(感谢@peceps)。


    这是一个禁用某个视图组的所有子视图的功能:

     /**
       * 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);
          }
        }
      }
    

    您可以在Fragment 的视图中调用此传递,由Fragment.getView() 检索。假设您的片段视图是ViewGroup

    【讨论】:

    • 这个解决方案的缺点是当一个视图在禁用所有视图时已经被禁用,它会在启用所有视图时启用。该函数可以返回所有已禁用视图的(弱)列表,因此您可以再次启用该列表,而不是启用所有内容。
    • @Marcel 绝对同意它可以改进。但是在发布 4 年后,无论是这个还是原来的答案,都没有得到改进。如果您想按照您的建议提供更新,我很乐意投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多