FindViewById返回错误的视图

时间:2016-06-26 12:35:16

标签: android findviewbyid

我使用ViewFlipper在两个相同的视图之间用动画交替。

此ViewFlipper的xml如下所示。

<ViewFlipper
    android:id="@+id/advise_viewflipper"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include android:id="@+id/product_select_one" layout="@layout/product_select_view" />
    <include android:id="@+id/product_select_two" layout="@layout/product_select_view" />
</ViewFlipper>

现在在我的片段中,我使用ButterKnife检索它们,并且获取它们的ID表明它们确实是两个不同的视图。

currentViewId = currentView.getId();
otherViewId = otherView.getId();
Log.d("Compare", currentView.getId() + " " + otherView.getId());

现在,在这两个相同的视图中,FlowLayout标识为advise_item_layout。但是,从两个视图查询此视图会返回相同的FlowLayout

如果我这样做:

final FlowLayout itemLayout = ButterKnife.findById(currentView, R.id.advise_item_layout);
final FlowLayout otherLayout = ButterKnife.findById(otherView, R.id.advise_item_layout);

Log.d("item vs other layout", itemLayout.getId() + " " + otherLayout.getId());

即使我传递了不同的视图,也会打印相同的ID? 使用Android的FindViewById时也是如此。

我知道FindViewById会进行深度优先搜索并抓取第一个匹配,但我明确指定了一个不同的视图来搜索?那么我做错了什么以及修复的是什么?

1 个答案:

答案 0 :(得分:1)

您错误地将getId()返回的视图标识符与视图引用标识相对应。视图标识符不需要是唯一的,并且视图层次结构具有多个具有相同标识符的视图。观点仍然是不同的对象。

  

Log.d("Compare", currentView.getId() + " " + otherView.getId());返回不同的ID。所以我很确定它们是不同的对象

是的,他们有不同的标识符,也有暗示,是不同的对象。

  

但是,Log.d("item vs other layout", itemLayout.getId() + " " + otherLayout.getId());报告了SAME ID,即使我将不同的父母传递给findById函数

是。两个视图可以具有相同的标识符。您可以使用深度优先第一次匹配搜索找到它们,因为您正在使用其他父级进行搜索。

如果您比较了对象引用

Log.d("item vs other layout", "" + itemLayout == otherLayout);

您会看到false被记录以实际验证它们是不同的视图对象。

相关问题