我在膨胀一个Android片段中的布局。要膨胀的布局具有以下包含标记:
<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"
/>我需要的视图引用的布局具有以下结构:
//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>我已经考虑过使用ViewTreeObserver对象来获取视图的引用,但是我已经使用了ViewTreeObserver,而且由于性能问题,我不想再次使用它。
我在onViewCreated方法中尝试了以下方法:
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!
} 如何通过findViewByID或findViewByTag调用获得对此ImageView的引用?
发布于 2022-07-10 19:39:29
findViewByID将递归地搜索整个树的层次结构。那就是你很容易打电话
fragmentView.findViewByID(R.id. my_image_view)在onCreateView或onViewCreated方法中
更新后,尝试使用:
onViewCreated(@NonNull View view, @Nullable Bundle
savedInstanceState)
{
AppCompatImageView imageview =
(AppCompatImageView)view.findViewById(R.id.my_image_view);
} 发布于 2022-07-10 21:17:37
好的,我找到了正确的答案:
在包含标记中,我们必须确保在包含的布局中具有与根视图相同的 id!
<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"
/>现在,在包含的布局的根视图中,即: middle_multi_game_card.xml
,我们必须有相同的ID的包含标签!来自上面: includeID
现在,我们可以从包含的布局中访问所有视图!
https://stackoverflow.com/questions/72931340
复制相似问题