2011-03-11 50 views
0

我对android很新颖......任何人都可以让我知道如何获得视图组的句柄?查看组实例

例如:

我在main.xml文件的线性布局。 我能够添加视图的唯一方法是 使用findViewById并指定线性布局的ID。我想开发它得到的ViewGroup中手柄和执行类似getChildCount() 等功能的通用方法...

回答

0

你可以让自己的布局子类,并覆盖一些方法,如onFinishInflate()View documentation有一些关于这方面的信息,你会发现很多有关如何做到这一点的教程。

这就是我在one of my tutorials解释得到布局的所有Checkable视图。

@Override 
protected void onFinishInflate() { 
    super.onFinishInflate(); 

    final int childCount = this.getChildCount(); 
    for (int i = 0; i < childCount; ++i) { 
     findCheckableChildren(this.getChildAt(i)); 
    } 
} 

/** 
* Add to our checkable list all the children of the view that implement the 
* interface Checkable 
*/ 
private void findCheckableChildren(View v) { 
    if (v instanceof Checkable) { 
     this.checkableViews.add((Checkable) v); 
    } 

    if (v instanceof ViewGroup) { 
     final ViewGroup vg = (ViewGroup) v; 
     final int childCount = vg.getChildCount(); 
     for (int i = 0; i < childCount; ++i) { 
      findCheckableChildren(vg.getChildAt(i)); 
     } 
    } 
} 
+0

谢谢。但我正在写一个泛型类,它获取所有EditText字段并将其发布到restful资源。所以我需要开发一个通用的代码,我可以在其他应用程序中使用。因此,我不想使用findViewById方法,在这种情况下特定于该应用程序。 – abhirami 2011-03-11 09:42:28

+0

Anwser编辑了一些代码 – 2011-03-11 09:49:05

+0

非常感谢! – abhirami 2011-03-11 10:36:17