Search code examples
androidandroid-layoutandroid-gallery

Android RelativeLayout Background Picture from Gallery


I have a problem to set background image for RelativeLayout. details problem : - I have RelativeLayout and Button in my UI. when button clicked then showing Gallery's intent. choose 1 picture from that gallery and i want to set that picture as RelativeLayout background.

I can call the intent for gallery, but i'm still fail to set that picture as RelativeLayout background. please help me

Edit (here's my example code to set ImageView from Gallery intent):

final ImageView img = (ImageView) findViewById(R.id.img);
    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
            //img.setImageResource(Intent.);
            Drawable dr = new BitmapDrawable(SELECT_PICTURE);
        }
    });
}

public void onActivityResult(int requestCode, int resultCode, Intent data){
    //Integer selectedImageUri;
    //Integer[] bg = {selectedImageUri};
    if (resultCode == RESULT_OK){
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
                      ImageView img = (ImageView) findViewById(R.id.img);
            img.setImageURI(selectedImageUri);

So how to set that picture not as image for ImageView, but as RelativeLayout background


Solution

  • After picking the picture from gallery, you can set the picture like this-

        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK)
            {
                Uri imageUri = data.getData();
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    
                RelativeLayout relative = (RelativeLayout) findViewById(R.id.relative1);
                Drawable dr = new BitmapDrawable(bitmap);
                relative.setBackgroundDrawable(dr);
            }
        }