MainActivity.java
package study_imageput.com.study_apktointent;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
//定义一个图片显示控件
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.ivPic);
String url = "http://images.cnitblog.com/blog/430074/201302/01220037-4e6a57c1199748fea9f8391e7e0548d7.jpg";
setPicBitmap(imageView, url);
}
public static void setPicBitmap(final ImageView ivPic,final String pic_url){
new Thread(new Runnable() {
@Override
public void run() {
try{
HttpURLConnection conn = (HttpURLConnection) new URL(pic_url).openConnection();
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bitmap =BitmapFactory.decodeStream(is);
ivPic.setImageBitmap(bitmap);
is.close();
} catch (Exception e){
e.printStackTrace();
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:text="加载图片"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/ivPic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#dc0000"/>
</LinearLayout>
AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="study_imageput.com.study_apktointent">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
最后显示结果就是白屏,如果之前设置了imageview的默认图片,加载之后就会变成白色