来自Gallery的Android RelativeLayout背景图片

时间:2013-11-29 10:18:21

标签: android android-layout android-gallery

我在为RelativeLayout设置背景图片时遇到问题。细节问题: - 我的用户界面中有RelativeLayoutButton。单击按钮然后显示Gallery的意图。从该图库中选择1张图片,我想将该图片设置为RelativeLayout背景。

我可以调用图库的意图,但我仍然无法将该图片设置为RelativeLayout背景。请帮帮我

修改(这是我从图库意图设置ImageView的示例代码):

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

那么如何将该图片设置为不是ImageView的图像,,而是设置为RelativeLayout背景

3 个答案:

答案 0 :(得分:1)

从图库中选择图片后,您可以像这样设置图片 -

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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

如果您正在获取可绘制资源,那么您可以使用该绘图来设置相对布局的背景,如下所示。

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

希望它会有所帮助。