2

在我main.xml中佈局,我有一個<FrameLayout>元素,這就是片段佔位符獲取片段的視圖,並禁用整個視圖

的main.xml:

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

我添加片段編程上述<FrameLayout>由:

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); 

但是,它不工作,我仍然可以點擊按鈕,在視圖。

+1

這裏檢查http://stackoverflow.com/questions/5418510/disable-the-touch-events-for-all-the-views和這裏http://stackoverflow.com/questions/7068873/how-can- i-disable-all-views-inside-the-layout – 2012-08-02 10:51:56

回答

7

根據@喬治的評論,這裏是從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

+0

該解決方案的缺點是,當禁用所有視圖時已經禁用視圖時,它將在啓用所有視圖時啓用。該函數可以返回被禁用的所有視圖的(弱)列表,因此您可以再次啓用該列表,而不是啓用所有內容。 – Marcel50506 2016-09-09 12:08:21

+0

@Marcel絕對認同它可以改進。但是發佈4年後,這個和原始答案都沒有得到改善。如果您想按照您的建議提供更新,我很樂意投票。 – 2016-09-09 14:27:11