Gooey Gooey - 3 months ago 39
Android Question

FindViewById returns wrong view

I use a

ViewFlipper
to alternate between two identical views with an animation.

The xml of this ViewFlipper is as follows.

<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>


Now in my fragment I retrieve both of them with ButterKnife, and fetching their IDs show that they are indeed two different views.

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


So now inside these two identical view is a
FlowLayout
with id
advise_item_layout
. However, querying this view from both views return the same
FlowLayout
.

If I do:

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());


The same ids are printed, even though I pass a different view?
The same holds when using FindViewById of Android.

I am aware that FindViewById does a depth first search and grabs the first match, but I am clearly specifying a different view to search in? So what am I doing wrong and what would be the fix?

Answer

You're mistaking view identifier as returned by getId() with view reference identity. View identifiers do not need to be unique and your view hierarchy has more than one view with the same identifier. The views are still different objects.

Log.d("Compare", currentView.getId() + " " + otherView.getId()); return different ids. So I am pretty sure they are different objects

Yes they have different identifiers and also by implication, are different objects.

However, Log.d("item vs other layout", itemLayout.getId() + " " + otherLayout.getId()); reports the SAME id, even though I pass different parents to the findById function

Yes. Two views can have the same identifier. You are able to find them with the depth-first first-match search since you're starting off the search with a different parent.

If you compared the object references

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

you'd see false being logged to actually verify they are different view object.