【问题标题】:Set gallery image as button background将图库图片设置为按钮背景
【发布时间】:2014-10-21 08:02:35
【问题描述】:

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

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

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

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

在显示相机意图后,我希望按钮将图像显示为背景 (android:background="mCurrent.....")???

如何做到这一点?

【问题讨论】:

    标签: android button


    【解决方案1】:

    这是解决方案。

    您不能仅通过路径或 URI 设置背景,您需要创建一个 Bitmap(并使用 ImageButton)或一个 Drawable。

    使用位图和图像按钮:

    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    yourImageButton.setImageBitmap(bitmap);
    

    使用 Drawable 和 Button:

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

    【讨论】:

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

    你看过这个问题了吗? How to set the button background image through code

    您不能在 xml 中执行此操作,只能以编程方式执行此操作。只需参考此处描述的新创建的图片: How to get path of a captured image in android

    【讨论】:

      【解决方案3】:

      启动相机意图:

      ...
      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 将其保存到文件中,然后读取该文件。详情在场here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 2013-03-05
        • 1970-01-01
        • 2013-09-27
        • 1970-01-01
        相关资源
        最近更新 更多