gpt4 book ai didi

android - 在 fragment 中处理相机

转载 作者:行者123 更新时间:2023-11-30 00:43:31 25 4
gpt4 key购买 nike

如有任何语法错误,请原谅。

我想在与 mainActivity 不同的 Activity 中使用相机。我在谷歌上找到了这个简单的教程 Taking Photos Simply ,也就是说我必须使用这个函数:

static final int REQUEST_IMAGE_CAPTURE = 1;

private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}

但是,这个函数只能在 MainActivity 中正常工作,事实上,如果我将这段代码放在不同的 Activity 中,我会得到这个错误:无法解析方法“getPackageManager()”。

一些想法?

谢谢!

最佳答案

试试下面的代码:

static final int REQUEST_IMAGE_CAPTURE = 1;

Context c;
private void dispatchTakePictureIntent() {
Fragment yourFragment = this;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
yourFragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}

覆盖父 Activity 的 onActivityResult():

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

然后将其添加到您的 fragment 中:

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
//Do something with your captured image. EX:-
try {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath))
} catch (FileNotFoundException e) {

e.printStackTrace();

}
}
}
}

关于android - 在 fragment 中处理相机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42186291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com