我正在尝试将Imageview设置为来自互联网的图片
这是我的xml代码
<ImageView
android:id="@+id/ivget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bg" />
这是我的java代码
ImageView test;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.getpic);
test = (ImageView) findViewById(R.id.ivget);
try{
String url1 = "http://www.esa.int/var/esa/storage/images/esa_multimedia/images/2012/11/glitter_galaxy/12136712-1-eng-GB/Glitter_Galaxy.jpg";
URL ulrn = new URL(url1);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
test.setImageBitmap(bmp);
else
Toast.makeText(getApplicationContext(), "Null", Toast.LENGTH_SHORT).show();
} catch(Exception e) {
}
}
当我运行应用程序时,imageview只与它设置的图片保持一致。如果删除imageview src,屏幕只是空白。
android清单具有Internet权限。
任何人都知道它为什么不起作用?
答案 0 :(得分:0)
使用后台线程从互联网下载任何内容并更新UI视图。
答案 1 :(得分:0)
您应该使用AsyncTask从服务器下载图像,如:
public class loadSingleView extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SingleImageViewActivity.this);
pDialog.setTitle("Connect to Server");
pDialog.setMessage("This process can take a few seconds to a few minutes, depending on your Internet Connection Speed.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// updating UI from Background Thread
try {
Intent in = getIntent();
big_image_url = in.getStringExtra(KEY_BIG_URL);
title = in.getStringExtra(KEY_TITLE);
artist = in.getStringExtra(KEY_ARTIST);
url = new URL(big_image_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String args) {
// dismiss the dialog after getting all products
TextView lblName = (TextView) findViewById(R.id.name_title);
TextView lblCost = (TextView) findViewById(R.id.name_artist);
lblName.setText(title);
lblCost.setText(artist);
ActionBar ab = getSupportActionBar();
ab.setTitle(title);
ab.setSubtitle(artist);
view = (ImageView) findViewById(R.id.single_image);
view.setImageBitmap(bmImg);
pDialog.dismiss();
}