【问题标题】:Can't load image with Picasso into fragment view无法使用毕加索将图像加载到片段视图中
【发布时间】:2014-09-04 23:27:17
【问题描述】:

我有一个片段,它假设用毕加索创建的 Imageview 填充背景。

public class Fragment1 extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Context c = getActivity().getApplicationContext();
        View myFragmentView = inflater.inflate(R.layout.home, container, false);
        TextView text = (TextView) myFragmentView.findViewById(R.id.text);

        ImageView imageView = (ImageView) myFragmentView.findViewById(R.id.image);
        String url = ModalScreens.byId(1).getBackgroundImagePath();
        Picasso.with(c).load(url).fit().into(imageView);
        return myFragmentView;
    }
}

我不知道我做错了什么,但图像无法加载。

【问题讨论】:

  • “url”字符串中返回了什么?它是有效路径吗?
  • onAttach() 为您提供片段附加到的 Activity,您可以确定,至少可以合理地确定,此时您有一个有效的 Activity。创建一个字段(推荐 mHost)并在 onAttach() 中分配 mHost = activity,然后在片段中需要 Activity 上下文的地方使用 mHost。这将有助于避免一些 NPE 问题,尽管这不是您上述问题的答案。 @adavis 确定了最可能的原因。

标签: android android-fragments picasso


【解决方案1】:

从您的代码看来,您加载的是本地资源而不是来自网络。如果是前者,那么你可以像这样加载它

StackOverflow showing image View from local disk

如果不是,并且您正在加载网络图像,那么这可能是各种问题,这里有一些希望对您有帮助的故障排除

  1. 你添加了吗?

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

  1. 链接是否有效(如建议的那样)?从头到尾没有空格什么的。我会做一个

Log.wtf("Testing valid URL", "|"+url+"|")

  1. 图像是否太大?在这种情况下,它可能会返回 null Image too large Stackoverflow answer

  2. Imageview 是否正确设置为显示?我会通过最初将其设置为这样的图像来确认 android:src="@mipmap/large 在您的 ImageView 布局 xml 中

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    相关资源
    最近更新 更多