【问题标题】:find all spinners that match a tag查找与标签匹配的所有微调器
【发布时间】:2012-06-05 23:10:16
【问题描述】:

是否可以获取列表或找到与特定标签匹配的所有Spinner

我希望用户能够即时添加新的Spinner 小部件,但我需要能够从每个Spinner 动态获取值。

jQuery 中,我可以选择与$('.myClassSelector').each() 匹配的所有元素。可以在 Android 中完成此操作或类似操作吗?

更新 所有微调器都位于 XML 中指定的特定 LinearLayout 中。布局用作所有微调器的容器。

【问题讨论】:

  • 遍历主布局树寻找微调器。
  • 您能详细说明您的要求吗?就像我们可以将所有微调器添加到 xml 中已经存在的相同线性布局中,还是我们需要根据需要将它们添加到不同的不同布局中。
  • 更新了帖子;它们都被添加到 XML 中指定的 LinearLayout 中。

标签: android spinner android-spinner


【解决方案1】:

我认为您可以获取之前添加Spinner 的布局的所有子项,并检查该子项是否为Spinner

    LinearLayout ll = //Your Layout this can be any Linear or Relative layout 
                     //in which you added your spinners at runtime ;

    int count = ll.getChildCount();
    for(int i =0;i<count;i++)
    {
        View v = ll.getChildAt(i);
        if(v instanceof Spinner)
        {
            // you got the spinner
            Spinner s = (Spinner) v;
            Log.i("Item selected",s.getSelectedItem().toString());
        }
    }

【讨论】:

    【解决方案2】:

    如果可能,最好将所有微调器添加到相同的线性布局中并使用 FasteKerinns 解决方案,但如果不可能,请尝试以下类似的操作.....

    Vector spinners = new Vector ():
    
    private void treverseGroup(ViewGroup vg)
    {
        final int count = vg.getChildCount();
        for (int i = 0; i < count; ++i)
        {
            if (vg.getChildAt(i) instanceof Spinner) 
            {
    
              spinners.add(vg.getChildAt(i));
            }
            else if (vg.getChildAt(i) instanceof ViewGroup)
                recurseGroup((ViewGroup) gp.getChildAt(i));
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      下面的方法能够检索整个视图层次结构中的所有 Spinner,以root 不使用递归。它还匹配给定的标签。

      private ArrayList<Spinner> getSpinners(ViewGroup root, Object matchingTag) {
          ArrayList<?> list = root.getTouchables();
      
          Iterator<?> it = list.iterator();
          while (it.hasNext()) {
              View view = (View) it.next();
              if (!(view instanceof Spinner && view.getTag().equals(matchingTag))) {
                  it.remove();
              }
          }
      
          return (ArrayList<Spinner>) list;
      }
      

      【讨论】:

      • 很有趣,我刚刚在我的项目中编写了这个方法来获取所有EditTexts。
      • 您可能需要在调用equals() 之前检查getTag() 的返回值是否为空。
      • 为什么不能对 textview 做同样的事情。Textt 视图不是可触摸的,那么它叫什么?
      猜你喜欢
      • 1970-01-01
      • 2016-11-11
      • 2010-10-31
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多