从工具栏中的片段访问 Imageview

Access Imageview from fragment in toolbar

我在工具栏中添加了 ImageView,工具栏位于 activity.How 中以访问片段中的工具栏图像。

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:theme="@style/AppTheme">

<TextView
    android:id="@+id/textToolHeader"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Header"
    android:textColor="@android:color/white"
    android:textSize="@dimen/txt_18"/>

<ImageView
    android:id="@+id/imgToolIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:layout_marginRight="@dimen/scale_10"
    android:src="@drawable/user"/>

</android.support.v7.widget.Toolbar>

我的片段代码如下:

toolbar = (Toolbar) mView.findViewById(R.id.toolbar);
imgToolIcon = (ImageView) toolbar.findViewById(R.id.imgToolIcon);
imgToolIcon.setImageDrawable(getResources().getDrawable(R.drawable.print));

请提供解决方案。

应该没有问题。只要它附加到 activity 那个片段,你就可以这样做:

ImageView iv = (ImageView) fragment.getView().findViewById(R.id.imgToolIcon);

你可以这样试试

imgToolIcon.setImageResource(R.drawable.print);

而不是这个

imgToolIcon.setImageDrawable(getResources().getDrawable(R.drawable.print));

最后我得到了如下解决方案:

ImageView imgToolIcon;
Toolbar toolbar;
TextView textToolHeader;

toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
imgToolIcon = (ImageView) toolbar.findViewById(R.id.imgToolIcon);
imgToolIcon.setImageResource(R.drawable.user);

这是准确的解决方案,有助于我在工具栏中设置自定义图像视图。