首先建立布局文件,main.xml,结构很简单,就一个输入框和一个按钮;
代码实现:
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android=""
-
android:orientation="vertical"
-
android:layout_width="fill_parent"
-
android:layout_height="fill_parent"
-
>
-
<TextView
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:text="请输入地址:"/>
-
<EditText
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:text=""
-
android:id="@+id/et_path"
-
android:hint="请输入地址"/>
-
<Button
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:text="查看图片"
-
android:id="@+id/bt_showpic"/>
-
<ImageView
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:id="@+id/iv_pic"/>
-
</LinearLayout>
接着创建一个工具类来处理图片请求,获取图片;
ImageUtil.java
-
public class ImageUtil {
-
public static Bitmap getBitmap(String path) throws Exception{
-
URL url = new URL(path);
-
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
conn.setConnectTimeout(5000);
-
conn.setRequestMethod("GET");
-
if (conn.getResponseCode()==200) {
-
InputStream iS = conn.getInputStream();
-
Bitmap bitmap = BitmapFactory.decodeStream(iS);
-
return bitmap;
-
}
-
return null;
-
}
-
}
主Activity类:
getPicFromNetActivity.java
-
public class getPicFromNetActivity extends Activity implements OnClickListener {
-
EditText et_path;
-
Button bt_showpic;
-
ImageView iv_pic;
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
//初始化参数
-
et_path = (EditText) this.findViewById(R.id.et_path);
-
bt_showpic=(Button) this.findViewById(R.id.bt_showpic);
-
iv_pic = (ImageView)this.findViewById(R.id.iv_pic);
-
//添加点击事件
-
bt_showpic.setOnClickListener(this);
-
}
-
@Override
-
public void onClick(View v) {
-
switch (v.getId()) {
-
case R.id.bt_showpic:
-
//获取输入文本
-
String path = et_path.getText().toString();
-
try {
-
//得到bitmap
-
Bitmap bitmap = ImageUtil.getBitmap(path);
-
//显示bitmap到界面
-
iv_pic.setImageBitmap(bitmap);
-
} catch (Exception e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
break;
-
}
-
}
-
}
运行结果:
阅读(2345) | 评论(0) | 转发(0) |