我正在开发一个项目,我需要捕捉图像并显示它的预览 对话框片段
对话框片段类如下:
public class DataImportDialog extends DialogFragment {
/******************************
* Capture management controls
* *************************
****************************/
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "MapirImages";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private Button btnCapturePicture;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog builder = new AlertDialog.Builder(getActivity())
.setTitle(R.string.ERROR)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.business_register,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
click(getView());
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
}
}
)
.setNegativeButton(R.string.business_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
}
})
.create();
View v = getActivity().getLayoutInflater().inflate(R.layout.data_import, null);
builder.setView(v);
btnCapturePicture = (Button) v.findViewById(R.id.btnCapturePicture);
/*
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// capture picture
captureImage();
// click(getView());
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
}
return builder;
}
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getActivity().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
getActivity().startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/*
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
@Override
public void onAttach(Activity act) {
// If the activity we're being attached to has
// not implemented the OnDialogDoneListener
// interface, the following line will throw a
// ClassCastException. This is the earliest we
// can test if we have a well-behaved activity.
try {
OnDialogDoneListener test = (OnDialogDoneListener) act;
} catch (ClassCastException cce) {
// Here is where we fail gracefully.
// Log.e(MainActivity.LOGTAG, "Activity is not listening");
}
super.onAttach(act);
}
现在,当我捕获图像并批准它时,我无法在dialogFragmnet类中获得图像捕获的结果。实际上我实现了像这样的OnActivityResult:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == getActivity().RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity().getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
这是我在其上加载dialogFragment的片段,如果用户长时间点击地图上的某个点,则会出现对话框并且他可以拍摄与该点相关的照片,并且我想要显示预览在同一对话框片段上拍摄的照片:
public class MyMapFragment extends SupportMapFragment
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener,
OnMarkerClickListener,
OnMapReadyCallback {
static final int PICK_EDIT_REQUEST = 1;
public static final int DIALOG_FRAGMENT = 1;
private Context mContext = null;
private GoogleMap mMap = null;
private GoogleApiClient mClient = null;
private String mLocString = null;
private Marker mLastClicked;
boolean markerClicked;
private float mAccuracy = 0;
private LatLng mLatLng = null;
DataImportDialog pdf;
public static MyMapFragment newInstance() {
MyMapFragment myMF = new MyMapFragment();
return myMF;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
getMapAsync(this);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = getActivity();
mClient = new GoogleApiClient.Builder(mContext, this, this)
.addApi(LocationServices.API)
.build();
mClient.connect();
}
@Override
public void onResume() {
super.onResume();
doWhenEverythingIsReady();
}
private void doWhenEverythingIsReady() {
if(mMap == null || mLocString == null)
return;
mMap.clear();
// Setup the info window for the marker
CustomInfoWindowAdapter ciwm = new CustomInfoWindowAdapter(mContext, mLocString);
mMap.setInfoWindowAdapter(ciwm);
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// Add the marker to the map
MarkerOptions markerOpt = new MarkerOptions()
.draggable(false)
.flat(true)
.position(mLatLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mLastClicked = mMap.addMarker(markerOpt);
mLastClicked.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
mMap.setOnMapClickListener(this);
mMap.setOnMapLongClickListener(this);
mMap.setOnMarkerClickListener(this);
markerClicked = false;
}
@Override
public void onMapClick(LatLng point) {
mMap.animateCamera(CameraUpdateFactory.newLatLng(point));
markerClicked = false;
}
@Override
public void onMapLongClick(LatLng point) {
mLatLng = point;
markerClicked = false;
FragmentTransaction ft = getFragmentManager().beginTransaction();
pdf = DataImportDialog.newInstance("Enter Something");
pdf.setTargetFragment(this, DIALOG_FRAGMENT);
Bundle args = new Bundle();
args.putDouble("Lat", point.latitude);
args.putDouble("Lng", point.longitude);
pdf.setArguments(args);
pdf.show(ft, "PROMPT_DIALOG_TAG");
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
Toast.makeText(mContext, "Connection failed", Toast.LENGTH_LONG).show();
}
@Override
public void onConnected(Bundle arg0) {
List<Address> here = null;
Toast.makeText(mContext, "Got connected", Toast.LENGTH_LONG).show();
FusedLocationProviderApi locator = LocationServices.FusedLocationApi;
Location myLocation = locator.getLastLocation(mClient);
// Toast.makeText(context, "My location is "+myLocation, Toast.LENGTH_LONG).show();
double lat = myLocation.getLatitude();
double lng = myLocation.getLongitude();
mAccuracy = myLocation.getAccuracy();
mLatLng = new LatLng(lat, lng);
Geocoder geo = new Geocoder(mContext);
try {
here = geo.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
mLocString = "Your current location:"
+ "\n" + here.get(0).getAddressLine(0)
+ "\n" + here.get(0).getAddressLine(1)
+ "\n" + here.get(0).getAddressLine(2);
doWhenEverythingIsReady();
}
@Override
public void onConnectionSuspended(int arg0) {
Toast.makeText(mContext, "Connection suspended", Toast.LENGTH_LONG).show();
}
@Override
public boolean onMarkerClick(Marker marker) {
// isInfoWindowShown() is broken so we need to keep track of what is
// showing ourselves. See this issue report for details:
// https://code.google.com/p/gmaps-api-issues/issues/detail?id=5408
if (mLastClicked != null && mLastClicked.equals(marker)) {
mLastClicked = null;
marker.hideInfoWindow();
return true;
} else {
mLastClicked = marker;
return false;
}
}
@Override
public void onMapReady(GoogleMap arg0) {
Toast.makeText(mContext, "Got a map", Toast.LENGTH_LONG).show();
mMap = arg0;
doWhenEverythingIsReady();
}
@Override
public void onDetach() {
super.onDetach();
mClient.disconnect();
if(mMap != null)
mMap.clear();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case DIALOG_FRAGMENT:
if (resultCode == Activity.RESULT_OK) {
mMap.addMarker(new MarkerOptions().position(mLatLng).title(mLatLng.toString()));
// After Ok code.
} else if (resultCode == Activity.RESULT_CANCELED){
// After Cancel code.
}
break;
}
}
}
在DataImportDialog类中,但在批准图像捕获后没有触发。
答案 0 :(得分:0)
使用强>
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
将onActiviyuresult
放在一边DataImportDialog片段
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == getActivity().RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity().getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}