Set Linear layout background dynamically

后端 未结 7 2397
南旧
南旧 2021-02-12 18:14

I wanted to set Linear Layout background dynamically in the following way:

  1. Fetch image from web url through XML parsing and then store that image into sd card.<

7条回答
  •  忘了有多久
    2021-02-12 18:46

    I have done this way:

    private RelativeLayout relativeLayout;
    

    onCreate:

    relativeLayout= (RelativeLayout)findViewById(R.id.relativeLayout);
    
    new LoadBackground("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg",
                "androidfigure").execute();
    

    AsyncTask to load image in background:

    private class LoadBackground extends AsyncTask {
    
        private String imageUrl , imageName;
    
        public LoadBackground(String url, String file_name) {
            this.imageUrl = url;
            this.imageName = file_name;
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    
        @Override
        protected Drawable doInBackground(String... urls) {
    
            try {
                InputStream is = (InputStream) this.fetch(this.imageUrl);
                Drawable d = Drawable.createFromStream(is, this.imageName);
                return d;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        private Object fetch(String address) throws MalformedURLException,IOException {
            URL url = new URL(address);
            Object content = url.getContent();
            return content;
        }
    
        @Override
        protected void onPostExecute(Drawable result) {
            super.onPostExecute(result);
            relativeLayout.setBackgroundDrawable(result);
        }
    }
    

    Hope this will help you.

提交回复
热议问题