如何将 AppCompatActivity 更改为 Fragment?

how to change AppCompatActivity to Fragment?

我是开发 android 应用程序的新手。

我想用“Droid Speech”但是我不能用,因为“Droid Speech”是由AppCompatActivity组成的。

我想知道如何把AppCompatActivity变成Fragment

这是我的代码

class DroidSpeechActivity : AppCompatActivity(), View.OnClickListener,
    OnDSListener,
    OnDSPermissionsListener {
    val TAG = "Activity_DroidSpeech"
    private var droidSpeech: DroidSpeech? = null
    private var finalSpeechResult: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_droid_speech)

        droidSpeech =
            DroidSpeech(this, fragmentManager)
        droidSpeech!!.setOnDroidSpeechListener(this)
        droidSpeech!!.setShowRecognitionProgressView(false)
        droidSpeech!!.setOneStepResultVerify(true)
        droidSpeech!!.setRecognitionProgressMsgColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyConfirmTextColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyRetryTextColor(Color.WHITE)
        droidSpeech!!.setPreferredLanguage("ko-KR")
        finalSpeechResult = findViewById(R.id.finalSpeechResult)
        start.setOnClickListener(this)
        stop.setOnClickListener(this)
    }

    override fun onPause() {
        super.onPause()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.start -> {

                // Starting droid speech
                droidSpeech!!.startDroidSpeechRecognition()

                // Setting the view visibilities when droid speech is running
                start!!.visibility = View.GONE
                stop!!.visibility = View.VISIBLE
            }
            R.id.stop -> {

                // Closing droid speech
                droidSpeech!!.closeDroidSpeechOperations()
                stop!!.visibility = View.GONE
                start!!.visibility = View.VISIBLE
            }
        }
    }

    // MARK: DroidSpeechListener Methods
    override fun onDroidSpeechSupportedLanguages(currentSpeechLanguage: String, supportedSpeechLanguages: List<String>) {
        Log.i(TAG, "Current speech language = $currentSpeechLanguage")
        Log.i(TAG, "Supported speech languages = $supportedSpeechLanguages")
        if (supportedSpeechLanguages.contains("ko-KR")) {
            // Setting the droid speech preferred language as tamil if found
            droidSpeech!!.setPreferredLanguage("ko-KR")

            // Setting the confirm and retry text in tamil
            droidSpeech!!.setOneStepVerifyConfirmText("check")
            droidSpeech!!.setOneStepVerifyRetryText("no")
        }
    }

    override fun onDroidSpeechRmsChanged(rmsChangedValue: Float) {
    }

    override fun onDroidSpeechLiveResult(liveSpeechResult: String) {
        Log.i(TAG, "Live speech result = $liveSpeechResult")
    }

    override fun onDroidSpeechFinalResult(finalSpeechResult: String) {
        this.finalSpeechResult!!.text = finalSpeechResult
        println("test$finalSpeechResult")
        if (droidSpeech!!.continuousSpeechRecognition) {
            val colorPallets1 = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA)
            val colorPallets2 = intArrayOf(Color.YELLOW, Color.RED, Color.CYAN, Color.BLUE, Color.GREEN)

            // Setting random color pallets to the recognition progress view
            droidSpeech!!.setRecognitionProgressViewColors(if (Random().nextInt(2) == 0) colorPallets1 else colorPallets2)
        } else {
            stop!!.visibility = View.GONE
            start!!.visibility = View.VISIBLE
        }
    }

    override fun onDroidSpeechClosedByUser() {
        stop!!.visibility = View.GONE
        start!!.visibility = View.VISIBLE
    }

    override fun onDroidSpeechError(errorMsg: String) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()
        stop!!.post {
            stop!!.performClick()
        }
    }

    // MARK: DroidSpeechPermissionsListener Method
    override fun onDroidSpeechAudioPermissionStatus(audioPermissionGiven: Boolean, errorMsgIfAny: String) {
        if (audioPermissionGiven) {
            start!!.post {
                start!!.performClick()
            }
        } else {
            if (errorMsgIfAny != null) {
                Toast.makeText(this, errorMsgIfAny, Toast.LENGTH_LONG).show()
            }
            stop!!.post {
                stop!!.performClick()
            }
        }
    }
}

这是尝试更改代码...但是错误

class DroidSpeechActivity : Fragment(), View.OnClickListener,
    OnDSListener,
    OnDSPermissionsListener {
    val TAG = "Activity_DroidSpeech"
    private var droidSpeech: DroidSpeech? = null
    private var finalSpeechResult: TextView? = null

    // MARK: Activity Methods
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Setting the layout;[.

        // Initializing the droid speech and setting the listener

        droidSpeech =
            DroidSpeech(activity?.applicationContext, activity?.getFragmentManager())
        droidSpeech!!.setOnDroidSpeechListener(this)
        droidSpeech!!.setShowRecognitionProgressView(false)
        droidSpeech!!.setOneStepResultVerify(true)
        droidSpeech!!.setRecognitionProgressMsgColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyConfirmTextColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyRetryTextColor(Color.WHITE)
        droidSpeech!!.setPreferredLanguage("ko-KR")
        start.setOnClickListener(this)
        stop.setOnClickListener(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.activity_droid_speech, container, false)
    }

    override fun onPause() {
        super.onPause()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    // MARK: OnClickListener Method
    override fun onClick(view: View) {
        when (view.id) {
            R.id.start -> {

                // Starting droid speech
                droidSpeech!!.startDroidSpeechRecognition()

                // Setting the view visibilities when droid speech is running
                start!!.visibility = View.GONE
                stop!!.visibility = View.VISIBLE
            }
            R.id.stop -> {

                // Closing droid speech
                droidSpeech!!.closeDroidSpeechOperations()
                stop!!.visibility = View.GONE
                start!!.visibility = View.VISIBLE
            }
        }
    }

    // MARK: DroidSpeechListener Methods
    override fun onDroidSpeechSupportedLanguages(currentSpeechLanguage: String, supportedSpeechLanguages: List<String>) {
        Log.i(TAG, "Current speech language = $currentSpeechLanguage")
        Log.i(TAG, "Supported speech languages = $supportedSpeechLanguages")
        if (supportedSpeechLanguages.contains("ko-KR")) {
            // Setting the droid speech preferred language as tamil if found
            droidSpeech!!.setPreferredLanguage("ko-KR")

            // Setting the confirm and retry text in tamil
            droidSpeech!!.setOneStepVerifyConfirmText("check")
            droidSpeech!!.setOneStepVerifyRetryText("no")
        }
    }

    override fun onDroidSpeechRmsChanged(rmsChangedValue: Float) {
        // Log.i(TAG, "Rms change value = " + rmsChangedValue);
    }

    override fun onDroidSpeechLiveResult(liveSpeechResult: String) {
        Log.i(TAG, "Live speech result = $liveSpeechResult")
    }

    override fun onDroidSpeechFinalResult(finalSpeechResult: String) {
        // Setting the final speech result
        this.finalSpeechResult!!.text = finalSpeechResult
        println("test$finalSpeechResult")
        if (droidSpeech!!.continuousSpeechRecognition) {
            val colorPallets1 = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA)
            val colorPallets2 = intArrayOf(Color.YELLOW, Color.RED, Color.CYAN, Color.BLUE, Color.GREEN)

            // Setting random color pallets to the recognition progress view
            droidSpeech!!.setRecognitionProgressViewColors(if (Random().nextInt(2) == 0) colorPallets1 else colorPallets2)
        } else {
            stop!!.visibility = View.GONE
            start!!.visibility = View.VISIBLE
        }
    }

    override fun onDroidSpeechClosedByUser() {
        stop!!.visibility = View.GONE
        start!!.visibility = View.VISIBLE
    }

    override fun onDroidSpeechError(errorMsg: String) {
        // Speech error
        stop!!.post { // Stop listening
            stop!!.performClick()
        }
    }

    // MARK: DroidSpeechPermissionsListener Method
    override fun onDroidSpeechAudioPermissionStatus(audioPermissionGiven: Boolean, errorMsgIfAny: String) {
        if (audioPermissionGiven) {
            start!!.post { // Start listening
                start!!.performClick()
            }
        } else {
            if (errorMsgIfAny != null) {
                // Permissions error
            }
            stop!!.post { // Stop listening
                stop!!.performClick()
            }
        }
    }
}

这是一条错误消息


java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.Jachi3kki.DroidSpeechActivity.onCreateView(DroidSpeechActivity.kt:49)

DroidSpeechActivity.kt:49行是这样的

start.setOnClickListener(this)

如何将我的 AppCompatActivity 转换为片段?

您的代码有一些问题:

  1. 通常最好使用可选的 ? 运算符并且不要强制使用 !! 进行转换以避免 NullPointerException
  2. 导致崩溃
  3. 您需要通过引用视图实例在 onCreateView 方法中初始化您的视图。
    与活动不同,片段不调用 setContentView 方法,因此您不能直接引用布局项。

在我的代码中,我使用了内联方法 setOnClickListener 并且我假设开始和停止是 Buttons, 如果不是这种情况,您只需要在声明中更改两个视图的类型即可。

尝试像这样更改片段的代码:

class DroidSpeechActivity : Fragment(), 
    OnDSListener,
    OnDSPermissionsListener {

    val TAG = "Activity_DroidSpeech"

    private var droidSpeech: DroidSpeech? = null
    private var finalSpeechResult: TextView? = null
    private var start: Button? = null
    private var stop: Button? = null

    // MARK: Activity Methods
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Initializing the droid speech and setting the listener
        droidSpeech = DroidSpeech(requireActivity().applicationContext, requireActivity().getFragmentManager()).apply {
            setOnDroidSpeechListener(this)
            setShowRecognitionProgressView(false)
            setOneStepResultVerify(true)
            setRecognitionProgressMsgColor(Color.WHITE)
            setOneStepVerifyConfirmTextColor(Color.WHITE)
            setOneStepVerifyRetryTextColor(Color.WHITE)
            setPreferredLanguage("ko-KR")
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.activity_droid_speech, container, false)

        finalSpeechResult = view.findViewById<TextView>(R.id.finalSpeechResult)

        start = view.findViewById<Button>(R.id.start).apply {
            setOnClickListener { startClicked() }
        }
        stop = view.findViewById<Button>(R.id.start).apply {
            setOnClickListener { stopClicked() }
        }

        return view
    }

    override fun onPause() {
        super.onPause()
        
        if (stop?.visibility == View.VISIBLE) {
            stop?.performClick()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        
        if (stop?.visibility == View.VISIBLE) {
            stop?.performClick()
        }
    }

    private fun startClicked() {
        droidSpeech?.startDroidSpeechRecognition()

        // Setting the view visibilities when droid speech is running
        start?.visibility = View.GONE
        stop?.visibility = View.VISIBLE
    }

    private fun stopClicked() {
        droidSpeech?.closeDroidSpeechOperations()

        stop?.visibility = View.GONE
        start?.visibility = View.VISIBLE
    }

    // MARK: DroidSpeechListener Methods
    override fun onDroidSpeechSupportedLanguages(currentSpeechLanguage: String, supportedSpeechLanguages: List<String>) {
        Log.i(TAG, "Current speech language = $currentSpeechLanguage")
        Log.i(TAG, "Supported speech languages = $supportedSpeechLanguages")
        if (supportedSpeechLanguages.contains("ko-KR")) {
            // Setting the droid speech preferred language as tamil if found
            droidSpeech?.setPreferredLanguage("ko-KR")

            // Setting the confirm and retry text in tamil
            droidSpeech?.setOneStepVerifyConfirmText("check")
            droidSpeech?.setOneStepVerifyRetryText("no")
        }
    }

    override fun onDroidSpeechRmsChanged(rmsChangedValue: Float) {
        // Log.i(TAG, "Rms change value = " + rmsChangedValue);
    }

    override fun onDroidSpeechLiveResult(liveSpeechResult: String) {
        Log.i(TAG, "Live speech result = $liveSpeechResult")
    }

    override fun onDroidSpeechFinalResult(finalSpeechResult: String) {
        // Setting the final speech result
        finalSpeechResult?.text = finalSpeechResult
        println("test$finalSpeechResult")
        if (droidSpeech?.continuousSpeechRecognition == true) {
            val colorPallets1 = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA)
            val colorPallets2 = intArrayOf(Color.YELLOW, Color.RED, Color.CYAN, Color.BLUE, Color.GREEN)

            // Setting random color pallets to the recognition progress view
            droidSpeech?.setRecognitionProgressViewColors(if (Random().nextInt(2) == 0) colorPallets1 else colorPallets2)
        } else {
            stop?.visibility = View.GONE
            start?.visibility = View.VISIBLE
        }
    }

    override fun onDroidSpeechClosedByUser() {
        stop?.visibility = View.GONE
        start?.visibility = View.VISIBLE
    }

    override fun onDroidSpeechError(errorMsg: String) {
        // Speech error
        stop?.post { // Stop listening
            stop?.performClick()
        }
    }

    // MARK: DroidSpeechPermissionsListener Method
    override fun onDroidSpeechAudioPermissionStatus(audioPermissionGiven: Boolean, errorMsgIfAny: String) {
        if (audioPermissionGiven) {
            start?.post { // Start listening
                start?.performClick()
            }
        } else {
            if (errorMsgIfAny != null) {
                // Permissions error
            }
            stop?.post { // Stop listening
                stop?.performClick()
            }
        }
    }
}