從網絡加載圖像時出現黑屏。將Web圖像加載到Android時出現黑色屏幕
我把網頁從網頁上轉到一個畫布,然後將其設置爲ImageView。
現在,當我加載它時,圖像中出現黑屏。
活動代碼:
public class ImageActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView i = (ImageView) findViewById(R.id.imageView1);
try {
String url = "http://www.rotoworld.com/images/headshots/NBA/1372.jpg";
Drawable image = ImageOperations(this, url);
i.setImageDrawable(image);
} catch (Exception ex) {
ex.printStackTrace();
}
i.setMinimumWidth(22);
i.setMinimumHeight(22);
i.setMaxWidth(22);
i.setMaxHeight(22);
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public Object fetch(String address) throws MalformedURLException, IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
謝謝!從來沒有聽說過AsyncTask。那裏有好的例子嗎? – user1163234 2012-02-02 09:25:46
@ user1163234文檔通常很不錯。 [AsyncTask]的文檔(http://developer.android.com/reference/android/os/AsyncTask.html)包含了一個關於如何使用它的例子。 – tidbeck 2012-02-02 09:42:09