片段中的UCrop没有发送requestCode

时间:2019-05-29 21:49:28

标签: android ucrop

我正在尝试从片段中使用Ucrop。我面临的问题是onActivityresult没有收到requestCode == UCrop.REQUEST_CROP,因此无法执行我需要对图像执行的操作。我到处搜索了教程,但找不到任何内容。

以下是使用UCrop的片段的代码:

public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == CAMERA_PERMISSIONS) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // All good so launch take picture from here
            dispatchTakePictureIntent();
        } else {
            // Permission denied. Warn the user and kick out of app
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.permsDeniedCameraTitle);
            builder.setMessage(R.string.permsDeniedCameraMessage);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Objects.requireNonNull(getActivity()).finishAffinity();
                }
            });
            builder.create().show();
        }
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        Uri starturi = Uri.fromFile(new File(currentPhotoPath));
        Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
        UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
        UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
    }

    Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);

    // On result from cropper add to imageview
    getActivity();
    if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        final Uri resultUri = UCrop.getOutput(data);
        assert resultUri != null;
        File imgFile = new File(resultUri.getPath());
        Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
        builder.listener(new Picasso.Listener() {
            @Override
            public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                exception.printStackTrace();
            }
        });
        builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
            @Override
            public void onSuccess() {
                btnSettingsSaveImage.setEnabled(true);
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = preferences.edit();
    View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
    imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
    ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
    btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);

    imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
        }
    });

    imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
        }
    });

    btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editor.putString("driver_picture", currentPhotoPath);
            editor.apply();
        }
    });

    Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
    builder.listener(new Picasso.Listener() {
        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
            exception.printStackTrace();
        }
    });

    Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));

    builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);

    return view;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.d("IMAGE CREATION", ex.toString());
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(getActivity(),
                    "com.mytestapp.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
    String imageFileName = "didimage_" + timeStamp + "_";
    File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,
            ".png",
            storageDir
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

}

正常活动中的相同代码可以正常工作。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

设法解决了这个问题。要将UCrop活动的结果传递给片段而不传递给宿主活动,您需要按以下方式调用UCrop....start()方法:

UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));

如此

.start(Context, Fragment)

这将确保调用片段的onActivityResult而不是托管活动之一。

答案 1 :(得分:0)

这也可以:

UCrop.of(sourceUri,destinationUri) .withOptions(选项) .start(getActivity(),YourFragment.this);

答案 2 :(得分:0)

如果您想从 Fragment 启动 uCrop 活动,请使用它。

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="5dp">

<TextView
    android:id="@+id/top_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Papaya (Around)"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

<TextView
    android:id="@+id/bottom_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=",(2kg)"
    app:layout_constraintTop_toBottomOf="@id/top_tv"
    app:layout_constraintStart_toStartOf="@id/top_tv"/>

<ImageView
    android:id="@+id/iv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher_help"
    app:layout_constraintTop_toTopOf="@id/bottom_tv"
    app:layout_constraintBottom_toBottomOf="@id/bottom_tv"
    app:layout_constraintStart_toEndOf="@id/bottom_tv"/>

</androidx.constraintlayout.widget.ConstraintLayout>