1、布局管理图片及代码
<ImageView
android:id="@+id/ivImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" />
<EditText
android:id="@+id/etImageUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="http://pica.nipic.com/2007-11-09/2007119124513598_2.jpg.jpg"
android:hint="请输入图片的地址" />
<Button
android:id="@+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="viewImage"
android:text="浏览" />
把需要的图片粘贴到drawable-hdpi文件夹下
2、在mainactivity类中进行功能实现
public class MainActivity extends Activity {
protected static final int SHOW_IMAGE = 0;
private ImageView ivNetImage;
private EditText etImageUrl;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etImageUrl=(EditText) findViewById(R.id.etImageUrl);
ivNetImage=(ImageView) findViewById(R.id.ivImage);
}
//1.在主线程中创建消息处理器
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
//2.进行消息处理
switch (msg.what){
case SHOW_IMAGE:
Bitmap bitmap=(Bitmap) msg.obj;
ivNetImage.setImageBitmap(bitmap);
break;
default:
break;
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void viewImage(View view) {
final String path=etImageUrl.getText().toString();//获取地址path
if(TextUtils.isEmpty(path)){
Toast.makeText(this, "图片路径不能为空", Toast.LENGTH_SHORT).show();
}else{
new Thread(){
public void run(){
//连接服务器
try {
URL url=new URL(path);
//发出http请求
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
//设置连接时间
httpURLConnection.setConnectTimeout(5000);
int responsecode=httpURLConnection.getResponseCode();
if(responsecode==200){
InputStream is=httpURLConnection.getInputStream();
Bitmap bitmap=BitmapFactory.decodeStream(is);
//2.告诉主线程,请帮我更新界面,内容是bitmap
Message msg=new Message();
msg.what=SHOW_IMAGE;
msg.obj=bitmap;
handler.sendMessage(msg);
}else{
Toast.makeText(MainActivity.this, "显示图片失败", Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
}