Fragment 上的图像裁剪器

问题描述 投票:0回答:0

让我们进入主要问题。我使用 https://github.com/ArthurHub/Android-Image-Cropper 作为图像裁剪器。我想从我的片段中打开这个 Image Cropper 活动。当我们选择图像时,它成功进入图像裁剪器部分,当我点击“裁剪”时。图像不想加载到我的图像视图中,我已经从活动结果中设置了ImageUri。

我想我仍然没有得到我的片段的活动结果。我已经尝试了一些尝试。但仍然没有用。我真的不明白片段和活动之间的活动结果是如何工作的。

这是我被卡住的片段。 (看看 onActivityresult)还有点击按钮“添加”的意图。

class EditProfileFragment : Fragment() {
    private lateinit var firebaseUser: FirebaseUser

    private var checkerAddProfile = ""
    private var checkerAddBackground = ""

    private var urlProfile = ""
    private var urlBackground = ""

    private var imageUriProfile: Uri? = null
    private var imageUriBackground: Uri? = null

    private var storageProfilePicRef: StorageReference? = null
    private var storageBackgroundPicRef: StorageReference? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val bind = FragmentEditProfileBinding.inflate(layoutInflater)

        firebaseUser = FirebaseAuth.getInstance().currentUser!!
        storageProfilePicRef = FirebaseStorage.getInstance().reference.child("Profile Pictures")
        storageBackgroundPicRef = FirebaseStorage.getInstance().reference.child("Background Pictures")

        bind.ivBackEditProfile.setOnClickListener {
            activity?.onBackPressed()
        }

        bind.ivAddProfilePhoto.setOnClickListener {
            addProfileImage()
        }

        bind.ivAddBgEditProfile.setOnClickListener {
            addBackgroundImage()
        }

        bind.btnSaveEditProfile.setOnClickListener {
            saveEditProfile(bind)
        }

        userInfo(bind)

        return bind.root
    }

    private fun saveEditProfile(bind: FragmentEditProfileBinding) {
        if (checkerAddProfile == "profile")
        {
            uploadImageAndUpdateInfo(bind)
        }
        if (checkerAddBackground == "background")
        {
            uploadImageBackgroundAndUpdateInfo(bind)
        }
        if (checkerAddProfile == "profile" && checkerAddBackground == "background")
        {
            uploadAllImageAndUpdateInfo(bind)
        }
        else{
            updateUserInfoOnly(bind)
        }
    }

    private fun uploadAllImageAndUpdateInfo(bind: FragmentEditProfileBinding) {
        when {
            imageUriProfile == null && imageUriBackground == null -> Toast.makeText(requireContext(), "Please select image first.", Toast.LENGTH_LONG).show()
            TextUtils.isEmpty(bind.etNameEditProfile.text.toString()) -> Toast.makeText(requireContext(), "Please write Username first.", Toast.LENGTH_LONG).show()
            bind.etBioEditProfile.text.toString() == "" -> Toast.makeText(requireContext(), "Please write your bio first.", Toast.LENGTH_SHORT).show()

            else -> {
                val progressDialog = ProgressDialog(requireContext())
                progressDialog.setTitle("Update Profile")
                progressDialog.setMessage("Please wait, we are updating your profile...")
                progressDialog.show()

                val fileProfileRef = storageProfilePicRef!!.child(firebaseUser!!.uid + ".jpg")
                val fileBackgroundRef = storageBackgroundPicRef!!.child(firebaseUser!!.uid + ".jpg")

                val uploadProfileTask: StorageTask<*>
                uploadProfileTask = fileProfileRef.putFile(imageUriProfile!!)

                val uploadBackgroundTask: StorageTask<*>
                uploadBackgroundTask = fileBackgroundRef.putFile(imageUriBackground!!)

                uploadProfileTask.continueWithTask(Continuation <UploadTask.TaskSnapshot, Task<Uri>>{ task ->
                    if (!task.isSuccessful)
                    {
                        task.exception?.let {
                            throw it
                            progressDialog.dismiss()
                        }
                    }
                    return@Continuation fileProfileRef.downloadUrl
                }).addOnCompleteListener { it ->
                    if (it.isSuccessful){
                        val downloadProfileUrl = it.result
                        urlProfile = downloadProfileUrl.toString()
                    }

                    uploadBackgroundTask.continueWithTask(Continuation <UploadTask.TaskSnapshot, Task<Uri>>{ task ->
                        if (!task.isSuccessful)
                        {
                            task.exception?.let {
                                throw it
                                progressDialog.dismiss()
                            }
                        }
                        return@Continuation fileProfileRef.downloadUrl
                    }).addOnCompleteListener { task ->
                        if (task.isSuccessful){
                            val downloadBackgroundUrl = task.result
                            urlBackground = downloadBackgroundUrl.toString()

                            val ref = FirebaseDatabase.getInstance().reference.child("User")

                            val userMap = HashMap<String, Any>()
                            userMap["userName"] = bind.etNameEditProfile.text.toString()
                            userMap["bio"] = bind.etBioEditProfile.text.toString()
                            userMap["link"] = bind.etLinkEditProfile.text.toString()
                            userMap["profile_image"] = urlProfile
                            userMap["background_image"] = urlBackground

                            ref.child(firebaseUser.uid).updateChildren(userMap)

                            Toast.makeText(requireContext(), "Account Information has been updated successfully.", Toast.LENGTH_LONG).show()

                            activity?.onBackPressed()
                            progressDialog.dismiss()
                        }
                        else
                        {
                            progressDialog.dismiss()
                        }
                    }
                }
            }
        }
    }

    private fun uploadImageBackgroundAndUpdateInfo(bind: FragmentEditProfileBinding) {
        when
        {
            imageUriBackground == null -> Toast.makeText(requireContext(), "Please select image first.", Toast.LENGTH_LONG).show()
            TextUtils.isEmpty(bind.etNameEditProfile.text.toString()) -> Toast.makeText(requireContext(), "Please write Username first.", Toast.LENGTH_LONG).show()
            bind.etBioEditProfile.text.toString() == "" -> Toast.makeText(requireContext(), "Please write your bio first.", Toast.LENGTH_SHORT).show()

            else -> {
                val progressDialog = ProgressDialog(requireContext())
                progressDialog.setTitle("Update Profile")
                progressDialog.setMessage("Please wait, we are updating your profile...")
                progressDialog.show()
                val fileRef = storageBackgroundPicRef!!.child(firebaseUser!!.uid + ".jpg")

                val uploadTask: StorageTask<*>
                uploadTask = fileRef.putFile(imageUriBackground!!)

                uploadTask.continueWithTask(Continuation <UploadTask.TaskSnapshot, Task<Uri>>{ task ->
                    if (!task.isSuccessful)
                    {
                        task.exception?.let {
                            throw it
                            progressDialog.dismiss()
                        }
                    }
                    return@Continuation fileRef.downloadUrl
                }).addOnCompleteListener (OnCompleteListener<Uri> { task ->
                    if (task.isSuccessful)
                    {
                        val downloadUrl = task.result
                        urlBackground = downloadUrl.toString()

                        val ref = FirebaseDatabase.getInstance().reference.child("User")

                        val userMap = HashMap<String, Any>()
                        userMap["userName"] = bind.etNameEditProfile.text.toString()
                        userMap["bio"] = bind.etBioEditProfile.text.toString()
                        userMap["link"] = bind.etLinkEditProfile.text.toString()
                        userMap["background_image"] = urlBackground

                        ref.child(firebaseUser.uid).updateChildren(userMap)

                        Toast.makeText(requireContext(), "Account Information has been updated successfully.", Toast.LENGTH_LONG).show()

                        activity?.onBackPressed()
                        progressDialog.dismiss()
                    }
                    else
                    {
                        progressDialog.dismiss()
                    }
                })
            }
        }
    }

    private fun uploadImageAndUpdateInfo(bind: FragmentEditProfileBinding) {
        when
        {
            imageUriProfile == null -> Toast.makeText(requireContext(), "Please select image first.", Toast.LENGTH_LONG).show()
            TextUtils.isEmpty(bind.etNameEditProfile.text.toString()) -> Toast.makeText(requireContext(), "Please write Username first.", Toast.LENGTH_LONG).show()
            bind.etBioEditProfile.text.toString() == "" -> Toast.makeText(requireContext(), "Please write your bio first.", Toast.LENGTH_SHORT).show()

            else -> {
                val progressDialog = ProgressDialog(requireContext())
                progressDialog.setTitle("Update Profile")
                progressDialog.setMessage("Please wait, we are updating your profile...")
                progressDialog.show()

                val fileRef = storageProfilePicRef!!.child(firebaseUser!!.uid + ".jpg")

                val uploadTask: StorageTask<*>
                uploadTask = fileRef.putFile(imageUriProfile!!)

                uploadTask.continueWithTask(Continuation <UploadTask.TaskSnapshot, Task<Uri>>{ task ->
                    if (!task.isSuccessful)
                    {
                        task.exception?.let {
                            throw it
                            progressDialog.dismiss()
                        }
                    }
                    return@Continuation fileRef.downloadUrl
                }).addOnCompleteListener (OnCompleteListener<Uri> { task ->
                    if (task.isSuccessful)
                    {
                        val downloadUrl = task.result
                        urlProfile = downloadUrl.toString()

                        val ref = FirebaseDatabase.getInstance().reference.child("User")

                        val userMap = HashMap<String, Any>()
                        userMap["userName"] = bind.etNameEditProfile.text.toString()
                        userMap["bio"] = bind.etBioEditProfile.text.toString()
                        userMap["link"] = bind.etLinkEditProfile.text.toString()
                        userMap["profile_image"] = urlProfile

                        ref.child(firebaseUser.uid).updateChildren(userMap)

                        Toast.makeText(requireContext(), "Account Information has been updated successfully.", Toast.LENGTH_LONG).show()

                        activity?.onBackPressed()
                        progressDialog.dismiss()
                    }
                    else
                    {
                        progressDialog.dismiss()
                    }
                } )
            }
        }
    }

    private fun updateUserInfoOnly(bind: FragmentEditProfileBinding) {
        when {
            TextUtils.isEmpty(bind.etNameEditProfile.text.toString()) -> Toast.makeText(requireContext(), "Please write Username first.", Toast.LENGTH_SHORT).show()
            bind.etBioEditProfile.text.toString() == "" -> Toast.makeText(requireContext(), "Please write your bio first.", Toast.LENGTH_SHORT).show()
            else -> {
                val usersRef = FirebaseDatabase.getInstance().reference.child("User")

                val userMap = HashMap<String, Any>()
                userMap["userName"] = bind.etNameEditProfile.text.toString()
                userMap["bio"] = bind.etBioEditProfile.text.toString()
                userMap["link"] = bind.etLinkEditProfile.text.toString()

                usersRef.child(firebaseUser.uid).updateChildren(userMap)

                Toast.makeText(requireContext(), "Account Information has been updated successfully.", Toast.LENGTH_LONG).show()
                activity?.onBackPressed()
            }
        }
    }

    private fun addBackgroundImage() {
        checkerAddBackground = "background"

        CropImage.activity()
            .setAspectRatio(2, 1)
            .start(requireContext(), this)
    }

    private fun addProfileImage() {
        checkerAddProfile = "profile"

        CropImage.activity()
            .setAspectRatio(1, 1)
            .start(requireContext(), this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    {
        super.onActivityResult(requestCode, resultCode, data)
        val bind = FragmentEditProfileBinding.inflate(layoutInflater)

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE  &&  resultCode == Activity.RESULT_OK  &&  data != null && checkerAddProfile == "profile")
        {
            val result = CropImage.getActivityResult(data)
            imageUriProfile = result.uri
            bind.ivAddProfilePhoto.setImageURI(imageUriProfile)
        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE  &&  resultCode == Activity.RESULT_OK  &&  data != null && checkerAddBackground == "background")
        {
            val result = CropImage.getActivityResult(data)
            imageUriBackground = result.uri
            bind.ivAddBgEditProfile.setImageURI(imageUriBackground)
        }
    }

    private fun userInfo(bind: FragmentEditProfileBinding) {
        val firebaseUser = FirebaseAuth.getInstance().currentUser!!
        val usersRef = FirebaseDatabase.getInstance().reference.child("User").child(firebaseUser.uid)

        usersRef.addValueEventListener(object : ValueEventListener
        {
            override fun onDataChange(snapshot: DataSnapshot)
            {
                for (p0 in snapshot.children){
                    val userName = snapshot.child("userName").value.toString()
                    val bio = snapshot.child("bio").value.toString()
                    val link = snapshot.child("link").value.toString()
                    val profileImage = snapshot.child("profile_image").value.toString()
                    val backgroundImage = snapshot.child("background_image").value.toString()

                    bind.etNameEditProfile.setText(userName)
                    bind.etBioEditProfile.setText(bio)
                    bind.etLinkEditProfile.setText(link)

                    Glide.with(requireContext()).load(profileImage).into(bind.ivAddProfilePhoto)
                    Glide.with(requireContext()).load(backgroundImage).into(bind.ivAddBgEditProfile)
                }
            }

            override fun onCancelled(p0: DatabaseError) {

            }
        })
    }

}

请帮助我的代码。谢谢。

android kotlin android-fragments onactivityresult image-cropper
© www.soinside.com 2019 - 2024. All rights reserved.