显示网络图片

MainActivity中的代码:


 public EditText etUrl;
 public ImageView picture;
 public static final int SHOW_IMAGE=0;
 private Handler handler=new Handler(){
 public void handlerMessage(android.os.Message msg){
   switch(msg.what){
   case SHOW_IMAGE:
    Bitmap bitmap=(Bitmap)msg.obj;
    picture.setImageBitmap(bitmap);
    break;
   default:
    break;
   }
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  findView();
 }
 public void findView(){
  etUrl=(EditText)findViewById(R.id.editText1);
  picture=(ImageView)findViewById(R.id.imageView1);
 }
 public void showImage(View view){//某button的onClick属性是此方法
  //final String path=etUrl.getText().toString();
  final String path="http://pic.sogou.com/d?query=%B0%D9%B6%C8%CD%BC%C6%AC%B4%F3%C8%AB&mood=0&picformat=0&mode=1&di=0&p=26050500&dp=1&did=5#did4";
  if(TextUtils.isEmpty(path)){
   Toast.makeText(this, "图片路径不能为空", Toast.LENGTH_SHORT).show();
  }
  else{
   new Thread(){
    public void run(){
     try{
      URL url=new URL(path);//创建地址
      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);
       Message msg=new Message();
       msg.what=SHOW_IMAGE;
       msg.obj=bitmap;
       handler.sendMessage(msg);//将msg转发给主线程中的handlerMessage管理,多线程中主线程以外的线程不能操控主布局文件中的控件。
      }
      else{
       Toast.makeText(MainActivity.this, "图片显示失败", Toast.LENGTH_SHORT).show();
       
      }
     }
     catch(MalformedURLException e){
      e.printStackTrace();
     }
     catch(IOException e){
      e.printStackTrace();
     }
    }
   }.start();
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值