You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SupportFragmentManager添加Fragment时add函数报错求助

问题:SupportFragmentManager添加Fragment时add函数报错

尝试使用SupportFragmentManager添加Fragment,但add函数被标红报错,错误提示:None of the following functions can be called with the arguments supplied。这段代码在另一个项目中可正常运行,当前项目代码及依赖配置如下:

项目代码

package com.example.homework4_task1.presentation.main

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.view.WindowCompat
import androidx.fragment.app.commit
import androidx.fragment.app.add
import com.example.homework4_task1.R
import com.example.homework4_task1.presentation.main.fragments.MainFragment

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

        fitContentViewToInsets()

        supportFragmentManager.commit {
            add<MainFragment> { 
                R.id.container
            }
        }
    }

    private fun fitContentViewToInsets() {
        WindowCompat.setDecorFitsSystemWindows(window, false)
    }

}

依赖配置

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.8.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.fragment:fragment-ktx:1.5.5'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

解决方案

问题出在add函数的调用语法上,你当前使用的fragment-ktx:1.5.5版本中,add<MainFragment>的重载并不支持用lambda块返回容器ID的写法。正确的调用方式是直接将容器ID作为参数传入:

修改后的代码:

supportFragmentManager.commit {
    add<MainFragment>(R.id.container)
    // 如需指定tag,可添加第二个参数:
    // add<MainFragment>(R.id.container, "MainFragmentTag")
}

如果另一个项目能正常运行,大概率是因为该项目使用了更高版本的fragment-ktx(比如1.6.0+),这些版本新增了支持lambda配置的重载,但1.5.5版本不兼容这种写法。你也可以选择升级fragment-ktx版本到1.6.0及以上,比如:

implementation 'androidx.fragment:fragment-ktx:1.6.1'

内容的提问来源于stack exchange,提问作者Student4543

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:38:29