标签:android
要获取网络上的图片,首先得有网络的访问权限,需要在AndroidManifest中添加相应权限,效果图:
布局文件如下:
<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" tools:context="${packageName}.${activityClass}" > <ImageView android:id="@+id/iv_img" android:layout_width="wrap_content" android:layout_height="300dp" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" /> <EditText android:id="@+id/et_url" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="60dp" android:inputType="textUri" android:text="@string/et_url"/> <Button android:id="@+id/btn_img" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:onClick="sendGetImg" android:text="@string/btn_img" /> </RelativeLayout>
import org.apache.http.Header; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; public class MainActivity extends Activity { private EditText et_url; private ImageView iv_img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_url=(EditText) findViewById(R.id.et_url); iv_img=(ImageView) findViewById(R.id.iv_img); } public void sendGetImg(View v){ int id=v.getId(); switch(id){ case R.id.btn_img: //获取网络路径 String url=et_url.getText().toString(); //创建客户端对象 AsyncHttpClient client=new AsyncHttpClient(); client.get(url, new AsyncHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if(statusCode==200){ BitmapFactory factory=new BitmapFactory(); Bitmap bitmap=factory.decodeByteArray(responseBody, 0, responseBody.length); iv_img.setImageBitmap(bitmap); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { error.printStackTrace(); } }); break; default: break; } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:android
原文地址:http://blog.csdn.net/cnshsh/article/details/46742757