Android 将库图像设置为按钮背景

Android 将库图像设置为按钮背景,android,button,Android,Button,我的代码中有一个按钮可以拍照: <Button android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/cameralogo" android:id="@+id/buttonCamera" /> 当我点击它时,它会打开相机并保存一张图片,路径是字符串mCurre

我的代码中有一个按钮可以拍照:

<Button
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/cameralogo"

            android:id="@+id/buttonCamera" />

当我点击它时,它会打开相机并保存一张图片,路径是字符串mCurrentPhotoPath

显示相机意图后,我希望按钮将图像显示为背景(android:background=“mCurrent…”


你是如何做到这一点的?

你已经看过这个问题了吗?

您不能在xml中这样做,而只能通过编程实现。只需参考新创建的图片,如下所述:

要启动摄像头,请执行以下操作:

...
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activity.startActivityForResult(takePictureIntent, PHOTO_ACTIVITY_REQUEST_CODE);
...
其中,PHOTO_ACTIVITY_REQUEST_CODE只是活动中唯一的整数常量,在启动结果意图时用作请求代码

在onActivityResult中接收照片,并更新视图背景

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PHOTO_ACTIVITY_REQUEST_CODE && data != null) {
    Bundle extras = data.getExtras();
    if (extras != null) {
        Bitmap photo = (Bitmap) extras.get("data");
        if (photo != null) {
            // mView should refer to view whose reference is obtained in onCreate() using findViewById(), and whose background you want to update
            mView.setBackground(new BitmapDrawable(getResources(), photo));
        }
    }
}
以上代码不使用全尺寸照片。为此,您必须要求Photo intent将其保存到文件中,然后读取该文件。详细信息已提供

以下是解决方案

您不能仅通过路径或URI设置背景,您需要创建位图(并使用ImageButton)或可从中绘制

使用位图和图像按钮:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
yourImageButton.setImageBitmap(bitmap);
使用Drawable和按钮:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Drawable d = new BitmapDrawable(getResources(),bitmap);
yourButton.setBackground(d);

是的,您需要在活动中使用它或使用上下文实例:Context.getContentResolver()。顺便说一下,如果您觉得我的解决方案有帮助,请给它打分:-)