如何使用活动和片段 (Kotlin)

How to work with activities and fragments (Kotlin)

我是应用程序开发和 Kotlin 的新手,我正在尝试开发我的第一个应用程序用于学习目的,但我有点迷路了。

现在,我有一个 activity 可以通过 firebase 登录我的应用程序的地方。然后我想做的是在活动之间进行的底部导航栏。通过一些教程,我发现最好的开发方式是通过片段而不是活动,但我不知道如何使用它们。

所以现在我有两个问题:

  1. 当我在登录后打开我的应用程序时如何做到这一点我的主要 activity 在单击按钮后直接显示一个片段:在第一张照片中你可以看到我的导航栏打开时选择了主页但是它的主要 activity 只有当我再次单击主页时才会转到 fragment

  1. 如何在片段中实现按钮并转到其他活动?例如,在我的个人资料片段上,我想要一个注销按钮,当我点击它时,它会转到我的登录 activity,但它总是崩溃并给我这个错误:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.appilerna, PID: 2263 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.button.MaterialButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at Fragments.ProfileFragment.logOut(ProfileFragment.kt:48) at Fragments.ProfileFragment.onCreateView(ProfileFragment.kt:42) at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002) at androidx.fragment.app.FragmentManager.run(FragmentManager.java:524) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7356) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

我的主要代码 activity:

    class MainActivity : AppCompatActivity() {

    private val calendarFragment = CalendarFragment()
    private val favoritesFragment = FavoritesFragment()
    private val profileFragment = ProfileFragment()
    private val homeFragment = HomeFragment()
    private val searchFragment = SearchFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        bottom_navigation.setOnItemSelectedListener { it:MenuItem ->
            when (it.itemId) {
                R.id.ic_home -> replaceFragment(homeFragment)
                R.id.ic_search -> replaceFragment(searchFragment)
                R.id.ic_favourites -> replaceFragment(favoritesFragment)
                R.id.ic_calendar -> replaceFragment(calendarFragment)
                R.id.ic_account -> replaceFragment(profileFragment)
            }
            true
        }
    }

    private fun replaceFragment(fragment: Fragment){
        if(fragment != null){
            val transaction = supportFragmentManager.beginTransaction()
            transaction.replace(R.id.fragment_container, fragment)
            transaction.commit()
        }
    }
}

我的主activityxml:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@color/backgroundColor" >

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bottom_navigation"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/menu"
        android:background="@color/salmon"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/fragment_container"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"/>

</androidx.constraintlayout.widget.ConstraintLayout>

我的 ProfileFragment 代码:

    // TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [ProfileFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class ProfileFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_profile, container, false)

        logOut(view)

        return view
    }

    fun logOut(view: View){
        logoutButton.setOnClickListener(View.OnClickListener {
            FirebaseAuth.getInstance().signOut()
            //view.context.startActivity(Intent(view.context, LogInActivity::class.java))
            val intent = Intent(activity, LogInActivity::class.java)
            activity?.startActivity(intent)
        })
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment ProfileFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic fun newInstance(param1: String, param2: String) =
                ProfileFragment().apply {
                    arguments = Bundle().apply {
                        putString(ARG_PARAM1, param1)
                        putString(ARG_PARAM2, param2)
                    }
                }
    }
}

我的个人资料片段xml:

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="Fragments.ProfileFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Profile"
        android:textSize="36sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/logoutButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="160dp"
        android:layout_marginLeft="160dp"
        android:layout_marginRight="163dp"
        android:layout_marginEnd="163dp"
        android:layout_marginBottom="16dp"
        android:text="LOG OUT"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

谢谢

编辑

我刚刚在 Main Activity:

上找到了第一个问题的答案
ft.replace(android.R.id.content, homeFragment)
    ft.commit()

    bottom_navigation.setOnItemSelectedListener { it: MenuItem ->
        when (it.itemId) {
            R.id.ic_home -> replaceFragment(homeFragment)
            R.id.ic_search -> replaceFragment(searchFragment)
            R.id.ic_favourites -> replaceFragment(favoritesFragment)
            R.id.ic_calendar -> replaceFragment(calendarFragment)
            R.id.ic_account -> replaceFragment(profileFragment)
        }
        true
    }
}

private fun replaceFragment(fragment: Fragment){
    if(fragment != null){
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(android.R.id.content, fragment)
        transaction.commit()
    }
}

但我的个人资料注销按钮仍然有问题。

抱歉,您的问题太宽泛无法回答,我认为您可以在本教程中找到所有问题的答案: https://www.youtube.com/watch?v=v8MbOjBCu0o

在这里您可以看到如何使用带有 android 底部导航栏的片段以及如何在片段中使用按钮点击侦听器

首先,您需要知道如何使用 NavHostNavController,我认为这个 link 会对您有所帮助。

您的崩溃解决方案- 你还没有初始化 MaterialButton

         fun logOut(view: View){
    //Add this line 
            **var logoutButton= view.findViewById<MaterialButton>(R.id.logoutButton)**  
//---------         
                    logoutButton.setOnClickListener(View.OnClickListener {
                        FirebaseAuth.getInstance().signOut()
                        //view.context.startActivity(Intent(view.context, LogInActivity::class.java))
                        val intent = Intent(activity, LogInActivity::class.java)
                        activity?.startActivity(intent)
                    })
                }