【问题标题】:ImageView In Fragment not showing片段中的 ImageView 未显示
【发布时间】:2017-03-17 13:55:51
【问题描述】:

我有一个奇怪的问题,我有一个解决方法,但想知道是否有人可以解释为什么会发生这种情况并可能有更优雅的解决方法?

我有一个带有一系列片段的 ViewPager。片段使用它们自己的布局,当 ImageView 添加到布局时,ImageView 不会在运行时呈现。

如果我在 Fragment 的 onCreateView 方法中为 ImageView 显式设置 imageDrawable(即使图像与布局 xml 中引用的图像相同,则图像显示正常。

这是我的片段 xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/baseRelLayout"
    android:background="@color/colorPrimary">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/flamerite_remote_6"
        android:layout_marginStart="36dp"
        android:id="@+id/remote6ButtonImage"
        android:layout_alignParentBottom="false"
        android:layout_alignStart="@+id/textView3"
        android:scaleType="fitXY"
        android:background="@color/colorPrimary"
        android:layout_alignBottom="@+id/remote9ButtonImage" />
</RelativeLayout>

这是我在 onCreateView 中重新设置可绘制图像的地方

public class WizardFragment extends Fragment {
    public static final String STEP_NUMBER = "STEP_NUMBER";

    public static  final WizardFragment newInstance(String message){
        WizardFragment f = new WizardFragment();
        Bundle bdl = new Bundle(1);
        bdl.putString(STEP_NUMBER,message);

        f.setArguments(bdl);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.wizard_fragment_step_1, container, false);
        ImageView remoteImage9Button = (ImageView)v.findViewById(R.id.remote9ButtonImage);
        remoteImage9Button.setImageDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.flamerite_remote_9, null)); //THIS IS THE LINE THAT MAKES THE IMAGE WORK AGAIN
        return v;
    }
}

我当然可以保留对 imageDrawable 的重新设置,但我觉得奇怪的是,仅在 xml 布局中设置时才显示图像

任何想法都非常感谢!

【问题讨论】:

  • 您已将 remote9ButtonImage 放入您的代码中,但它是您的 xml 中用于 id 的 remote6ButtonImage
  • 对不起,这段代码被简化了,实际上有 2 张图片,remote6 和 remote9,为了清楚起见,我在这里删除了其中一张,但显然不是一对!嗬!但在完整代码中,我正在为(remote6 和 remote9)设置图像
  • 那是矢量图吗?
  • 不,它只是一个 png
  • 然后尝试将其更改为android:src="@drawable/flamerite_remote_6"。它应该可以正常工作,但可能是一些奇怪的错误

标签: java android android-layout android-fragments android-imageview


【解决方案1】:

我不知道原因,但在我的情况下,当我更改时,同样的问题得到了解决

图片src定义来自

app:srcCompat="@drawable/logo"

android:src="@drawable/logo"

【讨论】:

    【解决方案2】:

    只需添加android:src="@drawable/logo" 而不是app:srcCompat

    【讨论】:

    • 是的,这对我有用。这个或“setImageResource”硬编码。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2012-08-18
    相关资源
    最近更新 更多