本文主要是介绍android开发之给LinearLayou设置网络图片作为背景,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.在onCreate()方法中获取LinearLayout控件
private LinearLayout personal_bg;personal_bg = findViewById(R.id.personal_bg);
2.在适当的地方调用如下方法:
new DownloadImageTask().execute("http://b.hiphotos.baidu.com/image/h%3D200/sign=025e31065dafa40f23c6c9dd9b65038c/10dfa9ec8a136327137e4407968fa0ec08fac777.jpg");
2.后台线程进行下载
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {protected Drawable doInBackground(String... urls) {return loadImageFromNetwork(urls[0]);}protected void onPostExecute(Drawable result) {personal_bg.setBackgroundDrawable(result);}}
3.公用方法
private Drawable loadImageFromNetwork(String imageUrl) {Drawable drawable = null;try {// 可以在这里通过第二个参数(文件名)来判断,是否本地有此图片drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), null);} catch (IOException e) {Log.d("skythinking", e.getMessage());}if (drawable == null) {Log.d("skythinking", "null drawable");} else {Log.d("skythinking", "not null drawable");}return drawable;}
这篇关于android开发之给LinearLayou设置网络图片作为背景的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!