我想在片段中添加url图片,但我无法做到。
URL imageUrl = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
public HomeFragment() throws MalformedURLException {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
try {
ImageView i = (ImageView)rootView.findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rootView;
}
显示错误
错误:(48,77)错误:不兼容的类型:无法转换为URL 串
错误:任务':app:compileDebugJavaWithJavac'执行失败。
编译失败;有关详细信息,请参阅编译器错误输出。
答案 0 :(得分:0)
您可以使用Picasso从网址加载图片。
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
或使用Glide
Glide.with(fragment).load(myUrl).into(imageView);
答案 1 :(得分:0)
试试这段代码:
public HomeFragment() throws MalformedURLException {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
try {
URL imageUrl = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
ImageView i = (ImageView)rootView.findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream());
i.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}