Android: Setting Background Image for RelativeLayout?

前端 未结 4 1538
耶瑟儿~
耶瑟儿~ 2021-01-04 04:31

I have downloaded an image at runtime. Now I want to set it as a background for RelativeLayout. Does it possible?

4条回答
  •  渐次进展
    2021-01-04 05:03

    In the onCreate function:

    RelativeLayout baseLayout = (RelativeLayout) this.findViewById(R.id.the_layout_id);
    
    Drawable drawable = loadImageFromAsset();
    
    if(drawable != null){
        baseLayout.setBackground(drawable);
        Log.d("TheActivity", "Setting the background");
    }
    

    The image loading method:

    public Drawable loadImageFromAsset() {
    
        Drawable drawable;
    
        // load image
        try {
    
            // get input stream
            InputStream ims = getAssets().open("images/test.9.png");
    
            //Note: Images can be in hierarical 
    
            // load image as Drawable
            drawable = Drawable.createFromStream(ims, null);
    
        }
        catch(IOException ex) {
            Log.d("LoadingImage", "Error reading the image");
            return null;
        }
    
        return drawable;
    }
    

    The open method:

    > public final InputStream open (String fileName, int accessMode)
    > 
    > Added in API level 1 Open an asset using an explicit access mode,
    > returning an InputStream to read its contents. This provides access to
    > files that have been bundled with an application as assets -- that is,
    > files placed in to the "assets" directory.
    > 
    > fileName --- The name of the asset to open. This name can be hierarchical.
    > 
    > accessMode --- Desired access mode for retrieving the data.
    > 
    > Throws IOException
    

提交回复
热议问题