Question

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

Was it helpful?

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

OTHER TIPS

Try this :

<ImageView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:scaleType="centerCrop"
        android:src="@drawable/background" />

If you are getting drawable resource then you can set background of relative layout using that drawable like the following.

  RelativeLayout relativeLayout;
  relativeLayout= (RelativeLayout) findViewById(R.id.layout1);
  RelativeLayout.setBackground(getResources().getDrawable(R.drawable.ic_launcher));

Hope it will help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top