标签:
查询网络图片
如图:
1、activity_main.xml布局
1 <ImageView 2 android:id="@+id/iv_img" 3 android:layout_width="wrap_content" 4 android:layout_height="300dp" 5 android:layout_alignParentLeft="true" 6 android:layout_alignParentRight="true" 7 android:layout_alignParentTop="true" 8 android:src="@drawable/ic_launcher" /> 9 10 <EditText 11 android:id="@+id/et_url" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:layout_alignParentBottom="true" 15 android:layout_alignParentLeft="true" 16 android:layout_marginBottom="60dp" 17 android:inputType="textUri" 18 android:text="@string/et_url"/> 19 20 <Button 21 android:id="@+id/btn_img" 22 android:layout_width="match_parent" 23 android:layout_height="wrap_content" 24 android:layout_alignParentBottom="true" 25 android:layout_alignParentLeft="true" 26 android:onClick="sendGetImg" 27 android:text="@string/btn_img" /> 28
2、MainActivity
1 public class MainActivity extends Activity { 2 3 private EditText et_url; 4 private ImageView iv_img; 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_main); 9 et_url=(EditText) findViewById(R.id.et_url); 10 iv_img=(ImageView) findViewById(R.id.iv_img); 11 } 12 13 public void sendGetImg(View v){ 14 int id=v.getId(); 15 switch(id){ 16 case R.id.btn_img: 17 //获取网络路径 18 String url=et_url.getText().toString(); 19 //创建客户端对象 20 AsyncHttpClient client=new AsyncHttpClient(); 21 client.get(url, new AsyncHttpResponseHandler(){ 22 @Override 23 public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { 24 if(statusCode==200){ 25 BitmapFactory factory=new BitmapFactory(); 26 Bitmap bitmap=factory.decodeByteArray(responseBody, 0, responseBody.length); 27 iv_img.setImageBitmap(bitmap); 28 } 29 } 30 31 @Override 32 public void onFailure(int statusCode, Header[] headers, 33 byte[] responseBody, Throwable error) { 34 error.printStackTrace(); 35 } 36 }); 37 break; 38 default: 39 break; 40 } 41 } 42 }
3、设置网络权限
<uses-permission android:name="android.permission.INTERNET"/>
4、创建异步客户端对象
5、获取uri网络路径
6、执行get请求
注意:decodeByteArray把字节转换成Bitmap对象
标签:
原文地址:http://www.cnblogs.com/j0820/p/4619903.html