How to programmatically change the background image of an Android Activity

前端 未结 3 1035
野性不改
野性不改 2021-02-06 05:24

I have been able to change colour of an activity background (see this post). Now a requirement is to do the same with background image. I mean I can click a button, select an op

3条回答
  •  甜味超标
    2021-02-06 06:23

    When you are setting background after selecting from Dialog then you are getting the resource id R.drawable.pix2 and retrieving the BitmapDrawable as follows...

    wvContent.setBackgroundColor(0);
    BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.pix2);
    bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
    wvContent.setBackgroundDrawable(bg);                    
    bg_color=R.drawable.pix2;
    

    But in onCreate() method you are just passing the resource id as below...

    wvContent.setBackgroundColor(getSelectedItem());
    

    where, getSelectedItem() returns an int value which is a resource id.

    Now, set background drawable as follows in onCreate() method...

    wvContent.setBackgroundColor(0);
    BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(getSelectedItem());
    bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
    wvContent.setBackgroundDrawable(bg);
    

    You can update background from SDCard as follows...

        String pathName = Environment.getExternalStorageDirectory().getPath() + "/folder/" + "image.jpg";
        Resources res = getResources(pathName);
        Bitmap bitmap = BitmapFactory.decodeFile(pathName);
        BitmapDrawable backgroundDrawable = new BitmapDrawable(res, bitmap);
        wvContent.setBackgroundDrawable(backgroundDrawable);
    

提交回复
热议问题