用异步来实现,上代码
activity_image.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ImageActivity" >
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progressBar1"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
ImageActivity.java
package com.example.asynctaskdemo;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class ImageActivity extends Activity {
ImageView imageView;
ProgressBar progressBar;
String url = "http://b.hiphotos.baidu.com/image/pic/item/7a899e510fb30f24eb4eecc9c195d143ac4b0327.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
imageView = (ImageView) findViewById(R.id.imageView);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
new MyAsyncTask().execute(url);//调用
}
class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);//进度条先设置不可见
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// TODO Auto-generated method stub
super.onPostExecute(bitmap);
progressBar.setVisibility(View.GONE);//图片显示后设置不可见
imageView.setImageBitmap(bitmap);
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
Bitmap bitmap = null;
try {
URLConnection connection = new URL(url).openConnection();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);//封装一下输入流
bitmap = BitmapFactory.decodeStream(bis);//解析
Thread.sleep(3000);
is.close();
bis.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
}
}
当然最后不要忘记在A你droidMnifest.xml加上权限
<uses-permission android:name="android.permission.INTERNET"/>