Instagram 克隆。单击按钮时,为啥我不能回到上一个片段?

Posted

技术标签:

【中文标题】Instagram 克隆。单击按钮时,为啥我不能回到上一个片段?【英文标题】:Instagram clone. when clicking a button, Why can't I go back to the previous fragment?Instagram 克隆。单击按钮时,为什么我不能回到上一个片段? 【发布时间】:2020-06-25 23:53:20 【问题描述】:

我真的可以在这方面使用你的帮助。 我正在制作 Instagram 克隆,我正在使用片段,我有一个用于个人资料页面。在其中,我有一个转到 AccountSettingsActivity 的按钮,您可以在其中编辑您的用户信息,我有一个按钮来保存更改,另一个按钮返回到配置文件片段,但是当我使用后者时,应用程序崩溃并出现此消息:

找不到明确的活动类 academy.epicprogramming.kynoanimalrescue/academy.epicprogramming.kynoanimalrescue.fragments.ProfileFragment; 您是否在 androidManifest.xml 中声明了此活动?

这是清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="academy.epicprogramming.kynoanimalrescue">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
<!--        <activity-->
<!--            android:name=".Main2Activity"-->
<!--            android:label="@string/title_activity_main2"></activity>-->
    <activity android:name=".AccountSettingsActivity" />
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBYtQl--ajXZy1uzOZoXSNGJLCeyAHUV9s" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity android:name=".Login.SignUpActivity" />
    <activity android:name=".Login.SignInActivity" />
    <activity android:name=".Intro.IntroSlider" />
    <activity android:name=".MainActivity" />
    <activity
        android:name=".Intro.SplashScreen"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
        android:theme="@style/Base.Theme.AppCompat"/> <!-- optional (needed if default theme         has no action bar) -->

</application>

</manifest>

这是返回 ProfileFragment 文件的按钮

close_profile_btn.setOnClickListener 

        val intent = Intent(this@AccountSettingsActivity, ProfileFragment::class.java)
        startActivity(intent)
        finish()
    

这是完整的 AccountSettingsActivity 文件

class AccountSettingsActivity : AppCompatActivity() 

private lateinit var firebaseUser: FirebaseUser
private var checker = ""
private var myUrl = ""
private var imageUri: Uri? = null
private var storageProfilePictureRef: StorageReference? = null


override fun onCreate(savedInstanceState: Bundle?)

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_account_settings)


    firebaseUser = FirebaseAuth.getInstance().currentUser!!
    storageProfilePictureRef =
        FirebaseStorage.getInstance().reference.child("Profile Pictures")

    logout_btn.setOnClickListener 
        FirebaseAuth.getInstance().signOut()

        val intent = Intent(this@AccountSettingsActivity, ProfileFragment::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
        finish()
    

    close_profile_btn.setOnClickListener 

        val intent = Intent(this@AccountSettingsActivity, ProfileFragment::class.java)
        startActivity(intent)
        finish()
    

    change_image_text_btn.setOnClickListener 
        checker = "clicked"

        CropImage.activity()
            .setAspectRatio(1, 1)
            .start(this@AccountSettingsActivity)
    

    save_info_profile_btn.setOnClickListener 
        if (checker == "clicked") 
            updateImageAndInfo()
         else 
            updateUserInfoOnly()
        
    

    userInfo()



override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) 
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE  &&  resultCode == Activity.RESULT_OK  &&  data != null)
    
        val result = CropImage.getActivityResult(data)
        imageUri = result.uri
        profile_image_view_profile_frag.setImageURI(imageUri)
    



private fun updateUserInfoOnly() 

    when 
        full_name_profile_frag.text.toString() == "" -> Toast.makeText(
            this,
            "Please enter your name",
            Toast.LENGTH_LONG
        ).show()

        username_profile_frag.text.toString() == "" -> Toast.makeText(
            this,
            "Please enter your username",
            Toast.LENGTH_LONG
        ).show()

        bio_profile_frag.text.toString() == "" -> 
            bio_profile_frag.setText("Estoy usando Kyno animal rescue")
            val usersRef =
                FirebaseDatabase.getInstance().reference.child("Users")
            val userMap = HashMap<String, Any>()
            userMap["fullname"] = full_name_profile_frag.text.toString().toLowerCase()
            userMap["username"] = username_profile_frag.text.toString()
            userMap["bio"] = bio_profile_frag.text.toString()

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

            Toast.makeText(this, "Account information successfully updated", Toast.LENGTH_LONG)
                .show()

            val intent = Intent(this@AccountSettingsActivity, MainActivity::class.java)
            startActivity(intent)
            finish()
        

        else -> 
            val usersRef =
                FirebaseDatabase.getInstance().reference.child("Users")
            val userMap = HashMap<String, Any>()
            userMap["fullname"] = full_name_profile_frag.text.toString().toLowerCase()
            userMap["username"] = username_profile_frag.text.toString()
            userMap["bio"] = bio_profile_frag.text.toString()

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

            Toast.makeText(this, "Account information successfully updated", Toast.LENGTH_LONG)
                .show()

            val intent = Intent(this@AccountSettingsActivity, MainActivity::class.java)
            startActivity(intent)
            finish()
        
    


private fun userInfo() 
    val usersRef =
        FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUser.uid)
    usersRef.addValueEventListener(object : ValueEventListener 
        override fun onDataChange(dataSnapshot: DataSnapshot) 

            if (dataSnapshot.exists()) 
                val user = dataSnapshot.getValue<User>(User::class.java)
                Picasso.get().load(user!!.getImage()).placeholder(R.drawable.profile)
                    .into(profile_image_view_profile_frag)
                full_name_profile_frag.setText(user.getFullname())
                username_profile_frag.setText(user.getUsername())
                bio_profile_frag.setText(user.getBio())
            
        

        override fun onCancelled(p0: DatabaseError) 
        
    )


private fun updateImageAndInfo() 

    when 
        imageUri == null -> Toast.makeText(
            this,
            "Please choose a picture",
            Toast.LENGTH_LONG
        ).show()

        full_name_profile_frag.text.toString() == "" -> Toast.makeText(
            this,
            "Please enter your name",
            Toast.LENGTH_LONG
        ).show()

        username_profile_frag.text.toString() == "" -> Toast.makeText(
            this,
            "Please enter your username",
            Toast.LENGTH_LONG
        ).show()

        bio_profile_frag.text.toString() == "" -> 
            Toast.makeText(
                this,
                "Please enter your bio",
                Toast.LENGTH_LONG
            ).show()
        

//            CODE TO SET A DEFAULT BIO IF USER DOESN'T ENTER ONE
//            bio_profile_frag.text.toString() == "" -> 
//                bio_profile_frag.setText("Estoy usando Kyno animal rescue")
//
//                val usersRef =
//                    FirebaseDatabase.getInstance().reference.child("Users")
//                val userMap = HashMap<String, Any>()
//                userMap["fullname"] = full_name_profile_frag.text.toString().toLowerCase()
//                userMap["username"] = username_profile_frag.text.toString()
//                userMap["bio"] = bio_profile_frag.text.toString()
//
//                usersRef.child(firebaseUser.uid).updateChildren(userMap)
//
//                Toast.makeText(this, "Account information successfully updated", Toast.LENGTH_LONG)
//                    .show()
//
//                val intent = Intent(this@AccountSettingsActivity, MainActivity::class.java)
//                startActivity(intent)
//                finish()
//            
        else -> 
            val progressDialog = ProgressDialog(this)
            progressDialog.setTitle("Account Settings")
            progressDialog.setMessage("Please wait while your profile updates")
            progressDialog.show()

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

            var uploadTask: StorageTask<*>
            uploadTask = fileRef.putFile(imageUri!!)

            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
                    myUrl = downloadUrl.toString()

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

                        val userMap = HashMap<String, Any>()
                        userMap["fullname"] =
                            full_name_profile_frag.text.toString().toLowerCase()
                        userMap["username"] = username_profile_frag.text.toString()
                        userMap["bio"] = bio_profile_frag.text.toString()
                        userMap["image"] = myUrl

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

                        Toast.makeText(
                                this,
                                "Account information successfully updated",
                                Toast.LENGTH_LONG
                            )
                            .show()

                        val intent =
                            Intent(this@AccountSettingsActivity, MainActivity::class.java)
                        startActivity(intent)
                        finish()

                        progressDialog.dismiss()

                     else 
                        progressDialog.dismiss()
                    

                
            )
        
    

【问题讨论】:

【参考方案1】:

Fragment cannot be started using Intent.

你必须做以下事情

supportFragmentManager
          .beginTransaction()
          .add(R.id.root_layout, ProfileFragment.newInstance(), "")
          .commit()

这里的add()方法第一个参数就是你要放到的容器 加载要提供其 id 的片段,第二个参数是 要加载的片段。

【讨论】:

【参考方案2】:

无法找到明确的活动类 academy.epicprogramming.kynoanimalrescue/academy.epicprogramming.kynoanimalrescue.fragments.ProfileFragment;您是否在 AndroidManifest.xml 中声明了此活动?

如果这是问题,那么您必须在清单文件中定义活动

您需要定义其他活动。

【讨论】:

【参考方案3】:

哦,天哪,这太简单了,在尝试了这么多东西之后,我在 Stack 的某个地方看到了一条评论,上面写着“你不需要 Intent,只需调用 finish()”,是的,这就是答案

【讨论】:

以上是关于Instagram 克隆。单击按钮时,为啥我不能回到上一个片段?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我第一次单击按钮时不能在 Qt Widget 上绘制点

Selenium 单击instagram Python上的所有关注按钮

为啥我不能在我的 Swift iOS 应用程序中使用 CIFilter 将我的图像反转回原始图像

让 Selenium 单击 Instagram 关注者按钮会引发错误“找不到元素”

在 asp.net webform 中单击按钮时避免回发

每当我在任何按钮(即 UISegmentedControl 按钮)之外单击时,都会单击该按钮。谁能告诉我为啥会这样?