【问题标题】:Is there any option to grab to more Views without ViewGroups?是否有任何选项可以在没有 ViewGroups 的情况下获取更多视图?
【发布时间】:2015-02-15 17:50:16
【问题描述】:

在 Android 中,您可以使用“id”选择一个视图,但是否有任何选项可以选择更多视图(如 CSS 中的“组”)?

例如,我想选择 View TextView,而不使用额外的 LayoutView。 有Group-Tag吗?还是有任何其他选项可以多次使用 id?

<View
        android:id="@+id/cardFront"
        android:layout_width="300dp"
        android:layout_height="407dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/image"
/>
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/string2"
/>

【问题讨论】:

    标签: android xml viewgroup


    【解决方案1】:

    您无法在单个 java 语句中找到多个 id。您需要为两个视图添加一个额外的父级。要同时选择您的 ViewTextView,您可以将它们都保存在 ViewGroup 中,然后尝试通过 id 找到它。

    【讨论】:

      【解决方案2】:

      只要您意识到这一点,ID 就可以被复制而不会造成任何损害。如果不想用id,有标签:

      <View
          android:id="@+id/cardFront"
          android:tag="myTag"
          android:layout_width="300dp"
          android:layout_height="407dp"
          android:layout_centerHorizontal="true"
          android:layout_centerVertical="true"
          android:background="@drawable/image"
      />
      <TextView
          android:tag="myTag"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/string2"
      />
      

      默认情况下,没有办法获得多个视图,但这很容易:

      public List<View> findViewsById(int id) {
          List<View> result = new ArrayList<>();
          List<ViewGroup> groups = new ArrayList<>();
          groups.add(this);
          while (!groups.isEmpty()) {
              ViewGroup group = groups.remove(0);
              for (int i = 0; i < group.getChildCount(); i++) {
                  View child = group.getChildAt(i);
                  if (child.getId() == id)
                      result.add(child);
                  if (child instanceof ViewGroup)
                      groups.add((ViewGroup) child);
              }
          }
          return result;
      }
      
      public List<View> findViewsWithTag(Object tag) {
          List<View> result = new ArrayList<>();
          List<ViewGroup> groups = new ArrayList<>();
          groups.add(this);
          while (!groups.isEmpty()) {
              ViewGroup group = groups.remove(0);
              for (int i = 0; i < group.getChildCount(); i++) {
                  View child = group.getChildAt(i);
                  if (tag.equals(child.getTag()))
                      result.add(child);
                  if (child instanceof ViewGroup)
                      groups.add((ViewGroup) child);
              }
          }
          return result;
      }
      

      【讨论】:

      • Woot,我以为现在有人问了这个问题。这是编辑
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2017-08-04
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多