2011-10-07 49 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 –

相关问题