2011-10-07 48 views
16

編程時是否可以通過編程實現特定佈局的所有子項?如何在Android中禁用/啓用LinearLayout上的所有孩子

,比如我有這樣的佈局有兩個孩子:

<LinearLayout android:layout_height="wrap_content" 
     android:id="@+id/linearLayout1" android:layout_width="fill_parent"> 
     <SeekBar android:layout_height="wrap_content" android:id="@+id/seekBar1" 
      android:layout_weight="1" android:layout_width="fill_parent"></SeekBar> 
     <TextView android:id="@+id/textView2" android:text="TextView" 
      android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" 
      android:layout_height="wrap_content"></TextView> 
    </LinearLayout> 

,我想這樣做:

LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearLayout1); 
myLayout.setEnabled(false); 

爲了禁用這兩個textviews。

任何想法如何?

回答

26

LinearLayout擴展了ViewGroup,因此您可以使用getChildCount()和getChildAt(index)方法迭代您的LinearLayout子元素並根據需要執行任何操作。我不確定你的意思是啓用/禁用,但如果你只是想隱藏它們,你可以做setVisibility(View.GONE);

所以,它會是這個樣子:

LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearLayout1); 
for (int i = 0; i < myLayout.getChildCount(); i++){ 
    View view = myLayout.getChildAt(i); 
    view.setVisibility(View.GONE); // Or whatever you want to do with the view. 
} 
+0

沒有使用setVisibility(View.GONE),可以在Android的LinearLayout上禁用/啓用所有的孩子 –

+0

我該如何做嵌套的Layout @ SBerg413 – Prabs

7

爲什麼不這樣做的佈局本身setVisibility(View.GONE),而不是通過迭代的孩子?

+0

你可能有一個包含其他的自定義視圖海關意見。您可能想要隱藏自定義視圖上的隨機視圖,而不是自定義視圖本身中的視圖。例如,在庫中很常見。如果您隱藏自定義視圖,則隱藏所有內容,而不僅僅是圖書館用戶添加的子視圖。 – Sotti

12

您也可以禁用/啓用不使用setVisibility()

添加View.OnClickListener到您的複選框,然後傳給你想被禁用爲以下功能查看...

private void enableDisableView(View view, boolean enabled) { 
    view.setEnabled(enabled); 

    if (view instanceof ViewGroup) { 
     ViewGroup group = (ViewGroup)view; 

     for (int idx = 0 ; idx < group.getChildCount() ; idx++) { 
      enableDisableView(group.getChildAt(idx), enabled); 
     } 
    } 
} 

以下參考Is there a way to disable all the items in a specific layout programmaticaly?

+5

來自http://stackoverflow.com/a/5257691/953010的明信片,你至少可以得到信任。 – PureSpider

0

只需添加另一個將原始視圖的match_parent的透明佈局,並將其可見性更改爲可見時,當您要禁用所有的孩子並啓用孩子,然後只是cha nge能見度不見

+0

您能否詳細說明您的答案,並添加關於您提供的解決方案的更多描述? – abarisone

+0

你可以在這裏查看http://stackoverflow.com/questions/10480560/how-to-disable-any-event-on-a-view-in-android –

相關問題