安卓:如何为RelativeLayout设置背景图片?

15
我在运行时下载了一张图片,现在我想将其设置为RelativeLayout的背景。这是否可能?
4个回答

23

请查看setBackgroundDrawable方法,或者在Drawable类中使用createFromPath方法。

   RelativeLayout rLayout = (RelativeLayout) findViewById (R.id.rLayout);
   Resources res = getResources(); //resource handle
   Drawable drawable = res.getDrawable(R.drawable.newImage); //new Image that was added to the res folder

    rLayout.setBackground(drawable);

1
是的,您可以使用createFromPath从新下载的图像所在路径创建一个Drawable对象。 - SteD

5

请改用以下方式:

View lay = (View) findViewById(R.id.rLayout);
lay.setBackgroundResource(R.drawable.newImage);

这是因为R.drawable.newImage指的是一个整数。所以你可以这样做:
int pic = R.drawable.newImage;
lay.setBackgroundResource(pic);

2
尝试使用此方法进行Xamarin.Android(跨平台)开发 -
RelativeLayout relativeLayout = new RelativeLayout (this);

或者

RelativeLayout relativeLayout = (RelativeLayout)FindViewById (Resource.Id.relativeLayout);

relativeLayout.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.imageName));

0
在 onCreate 函数中:
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");
}

图片加载方法:

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;
}

开放方法:

> 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接