Home > database >  Finding reference to ImageView via an include tag in Android xml layout
Finding reference to ImageView via an include tag in Android xml layout

Time:07-11

I am inflating a layout inside an Android Fragment. The layout to be inflated has the following include tag:

<include layout="@layout/middle_multi_game_card"  //NEED TO LOCATE VIEW INSIDE THIS LAYOUT
    android:id="@ id/includeID"
    android:tag="@ id/big_game_card_tag"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="6"
    />

The layout in which the view reference I need has the following structure:

//middle_multi_game_card:

<androidx.coordinatorlayout.widget.CoordinatorLayout
  android:id="@ id/theroot_"
 >

<androidx.constraintlayout.widget.ConstraintLayout

>

</androidx.constraintlayout.widget.ConstraintLayout>

<androidx.appcompat.widget.AppCompatImageView   // **I NEED A REFERENCE TO THIS VIEW!**
 android:id="@ id/my_image_view"
 android:tag="thegamepiece_"
</androidx.appcompat.widget.AppCompatImageView>

 
</androidx.coordinatorlayout.widget.CoordinatorLayout>

I have thought of using a ViewTreeObserver object to get the reference to the view, but I already use the ViewTreeObserver and I don't want to use it again because of performance issues.

I have tried the following inside onViewCreated method:

onViewCreated(@NonNull View view, @Nullable Bundle 
savedInstanceState)
{ 
View viewf = view.findViewById(R.id.includeID); //this is found!!
View view_ = viewf.findViewById(R.id.theroot_); //not found at all!
 imageview = 
(AppCompatImageView)view_.findViewById(R.id.my_image_view);//not found at all!
} 

How can I get a reference to this ImageView via findViewByID or findViewByTag calls?

CodePudding user response:

The findViewByID will recursively search the whole tree hierarchy. That being that you easily call

fragmentView.findViewByID(R.id. my_image_view)

in your onCreateView or onViewCreated methods

Updated, try to use:

onViewCreated(@NonNull View view, @Nullable Bundle 
savedInstanceState)
{ 
AppCompatImageView imageview = 
(AppCompatImageView)view.findViewById(R.id.my_image_view);
} 

CodePudding user response:

Ok I was able to find the correct answer:

in the include tag we have to make sure we have the same android id of the root view within the included layout!

<include layout="@layout/middle_multi_game_card"  //NEED TO LOCATE VIEW INSIDE THIS LAYOUT
android:id="@ id/includeID"
android:tag="@ id/big_game_card_tag"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="6"
/>

Now, in the root view of the included layout, which is: middle_multi_game_card.xml

WE MUST HAVE THE SAME ID OF THE INCLUDE TAG! WHICH IS FROM ABOVE: includeID

Now, we can access all the views from inside the included layout!

  • Related