Android Fragments 如何解决在Kotlin中将MainActivity转换为片段时出现的“类型不匹配”和“未解析引用”错误?[duplicate]

t2a7ltrp  于 2023-02-23  发布在  Android
关注(0)|答案(1)|浏览(180)
    • 此问题在此处已有答案**:

Hello, I have updated my activity class as fragment, but I am not sure how to update the parts in the photo(3个答案)
8小时前关门了。
我正在尝试将我的MainActivity.kt转换成一个Fragment,所以到目前为止,代码的开头看起来是这样的:

class MainActivity : Fragment() {
lateinit var mAdView : AdView    private lateinit var progressDialog: ProgressDialog
private var selectedtype = "Ultra fast"
private val binding by lazy {
    ActivityMainBinding.inflate(layoutInflater)
}


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.main_activity, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    //setContentView(binding.root)
    progressDialog = ProgressDialog(this)
    progressDialog.setCancelable(false)
    progressDialog.setCanceledOnTouchOutside(false)
    inIt()
    MobileAds.initialize(this) {}
    mAdView = view.findViewById(R.id.adView)
    val adRequest = AdRequest.Builder().build()
    mAdView.loadAd(adRequest)
    
    getSupportActionBar()?.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM)
    getSupportActionBar()?.setCustomView(R.layout.actionbar_title)

}

我有这个错误:
类型不匹配:推断类型为MainActivity,但应为Context!
此处:

progressDialog = ProgressDialog(this)

这里:

MobileAds.initialize(this) {}

和这个错误:
未解析的引用:获取支持操作栏
此处:

getSupportActionBar()?.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM)
getSupportActionBar()?.setCustomView(R.layout.actionbar_title)

我该怎么解决这些问题呢?

y53ybaqx

y53ybaqx1#

ActivityFragment不同,不能简单地将AppCompatActivity更改为Fragment
要从Fragment取回对应的Activity,必须使用getActivity()
所以,
进度对话框=进度对话框(此)
您应该:

progressDialog = ProgressDialog(activity)

以及:
获取支持操作栏()?...
您应该:

(activity as AppCompatActivity).supportActionBar...

请注意,要使用getSupportActionBar(),您的Activity必须是AppCompatActivity

相关问题