我在服务器网址中有图像,然后我正在传递并显示到卡片中。我在android中使用LoaderImageView库并显示但是在Glass中我将url链接传递给了卡片。但是我得到了这个错误“CardBuilder类型中的方法addImage(Drawable)不适用于参数(String)”
代码:
public static Drawable drawableFromUrl(String url) {
Bitmap x;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
} catch(MalformedURLException e) {
//Do something with the exception.
}
catch(IOException ex) {
ex.printStackTrace();
}
return null;
}
View view = new CardBuilder(getBaseContext(), CardBuilder.Layout.TITLE)
.setText("TITLE Card")
// .setIcon(R.drawable.ic_phone)
.addImage(drawableFromUrl(link))
.getView();
答案 0 :(得分:1)
From the doc,addImage采用Drawable,int或Bitmap。它不需要String。
您可以使用AsyncTask或线程或任何您喜欢的内容下载图像并将其转换为Drawable。然后,您可以调用addImage。
例如:
// new DownloadImageTask().execute("your url...")
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
// yourCardBuilder.addImage(link)
// or start another activity and use the image there...
}
}
public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
我没有对代码进行测试,但希望您明白这一点。
另见:
修改强>
private Drawable drawableFromUrl(String url) {
try {
Bitmap bitmap;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return new BitmapDrawable(bitmap);
} catch (IOException e) {
return null;
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
stopSlider();
if(result != null) {
mCardAdapter.setCards(createCard(getBaseContext(), result));
mCardAdapter.notifyDataSetChanged();
}
}
}
请参阅my GitHub repo上的完整示例。 SliderActivity可能对您有所帮助。