在 MainActivity 中实现回调:预期成员声明错误

Implementing CallBacks in MainActivity: Expecting Member Declaration Error

我正在尝试在 Main Activity 上实现回调,因此我可以根据用户行为切换片段。我在 onCreate CrimeListFragment.Callbacks 上面实现了它,但是我得到了一个错误(期待成员声明)

package com.bignerdranch.android.criminalintent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.util.*


class MainActivity : AppCompatActivity() {
    /*
    Implementing callbacks inside the hosting activity to change the fragment once needed.
     */
    CrimeListFragment.Callbacks {

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


            /*
      to add a fragment into activity in code, we call FragmentManager.
      we instantiate the fragment with the fragment manager. and set the condition to show it
      in case it is null, call fragment manager to start transaction and add the fragment container
      as the view and its code file CrimeFragment() in action, then commit them to OS.

      transactions are used to add, remove, attach, detach or replace a fragment
       */
            val currentFragment = //<--  When we need to retrieve the CrimeFragment from
                // the fragment manager you asked for it by container view ID
                supportFragmentManager.findFragmentById(R.id.fragment_container)

            if (currentFragment == null) {
                val fragment = CrimeListFragment.newInstance()
                supportFragmentManager
                    .beginTransaction()
                    .add(R.id.fragment_container, fragment)
                    .commit()
            }

        }


        override fun onCrimeSelected(crimeid: UUID) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.fragment_container, CrimeFragment())
                .commit()
        }
    }
}

您缺少保留字class

class CrimeListFragment.Callbacks {...

这不是回调实现,而是内部 class 声明。

此外,您正在从那里的片段编写方法,但您没有扩展片段

class CrimeListFragment.Callbacks : Fragment {

如果您已经在 CrimeListFragment 中定义了 CrimeListFragment.Callbacks interface,那么您要做的是:

class MainActivity : AppCompatActivity(), CrimeListFragment.Callbacks {

这将迫使您在 activity.

中实施 interface CrimeListFragment.Callbacks 中定义的方法