【问题标题】:Access Imageview from fragment in toolbar从工具栏中的片段访问 Imageview
【发布时间】:2015-07-02 10:10:22
【问题描述】:

我在工具栏中添加了 ImageView 并且工具栏处于活动状态。如何访问片段中的工具栏图像。

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

请提供解决方案。

【问题讨论】:

  • 请把你的Toolbar片段代码也贴在这里。
  • 我担心自从您在下面添加自我回答后,此问题已被多次修改。这通常不是问题,但是由于您已经承认在其他一些帖子中用新问题覆盖了旧问题,所以我想确保这里不会发生这种情况。以下所有的答案是否仍然适用于问题的新措辞?

标签: android imageview fragment toolbar android-fragmentactivity


【解决方案1】:

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

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

这是对我在工具栏中设置自定义图像视图很有帮助的确切解决方案。

【讨论】:

    【解决方案2】:

    你可以这样试试

    imgToolIcon.setImageResource(R.drawable.print);
    

    不是这个

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

    【讨论】:

      【解决方案3】:

      应该没有问题。只要它附加到该片段的活动,您就可以执行以下操作:

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

      【讨论】:

      • 什么是片段?请详细说明
      • fragment 是包含该工具栏的片段。
      • 哪一个?您确定片段中有带有工具栏的布局吗?
      • 是的。但是您的代码不起作用。感谢您的努力,我得到了解决方案
      • 请添加答案,以便其他人也可以享受它!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      相关资源
      最近更新 更多