setBackground from Bitmap API 22+

256 Views Asked by At

I have an app that can take a selected image from the users gallery and display it as their background within the app. I have used the code below with success.

Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
BitmapDrawable drawable = new BitmapDrawable(getResources(), BitmapFactory.decodeFile(picturePath));
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
    llmain.setBackgroundDrawable(drawable);
} else if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
    llmain.setBackground(drawable);
}

Although, since I have updated my app to API 22 it has stopped working. I have found how to set the background with

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
    llmain.setBackgroundDrawable(drawable);
} else if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
    llmain.setBackground(drawable);
} else {
    llmain.setBackground(ContextCompat.getDrawable(this, drawable));
}

But it doesn't work since the ContextCompat.getDrawable() call is for context and an int and not context and a BitmapDrawable.

2

There are 2 best solutions below

2
Joy On

Little change your code i hope it's help for you

Updated:

Uri selectedImage = data.getData();
    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();
    Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
    BitmapDrawable background = new BitmapDrawable(getApplicationContext().getResources(),bitmap);
    llmain.setBackground(background);
2
ViramP On

Set Bitmap as background to linear layout.

Directly you can't set bitmap to layout so you should use BitmapDrawable which convert bitmap to drawable.

BitmapDrawable background = new BitmapDrawable(bmImg);
linearLayout.setBackgroundDrawable(background);