android 如何拍摄照片并将其设置为我的ImageButton,而不使用已弃用的方法startActivityForResult()?

vu8f3i0k  于 4个月前  发布在  Android
关注(0)|答案(1)|浏览(62)

这是我现在的代码:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 0 && resultCode == AppCompatActivity.RESULT_OK) {
            ibPic.setImageBitmap((Bitmap) data.getExtras().get("data"));
        }
    }

字符串
我尝试使用ActivityResultLauncherregisterForActivityResult(),但它没有工作。

ujv3wf0j

ujv3wf0j1#

现在您可以使用ActivityResultLauncher来实现,具体步骤如下:

1.注册

  • 使用registerForActivityResult与选定的合约和结果回调。
    2.启动
  • 在ActivityResultLauncher上将startActivityForResult替换为launch。
    3.处理结果
  • 从回调中的ActivityResult对象提取结果信息。

例如
public class Jumper {

private ImageButton imageButton;
private ActivityResultLauncher<Intent> cameraLauncher;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    imageButton = findViewById(R.id.your_image_button_id);

    // Set up the camera launcher for handling the result
    cameraLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                handleCameraResult(result);
            }
        }
    );

    // Set a click listener to open the camera when the image button is clicked
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openCamera();
        }
    });
}

// Function to open the camera
private void openCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        cameraLauncher.launch(takePictureIntent);
    }
}

// Function to handle the camera result. Handling Results**strong text**
private void handleCameraResult(ActivityResult result) {
    if (result.getResultCode() == RESULT_OK) {
        Intent data = result.getData();
        if (data != null && data.getExtras() != null) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            imageButton.setImageBitmap(photo);
        }
    }
}

字符串
}

相关问题