我是android的新手,我正在开发一个Activity,它将动态显示到FrameLayout中(参见下面的代码)。 我希望在显示特定片段时启用Button(包含在MainActivity中)。
我发现在片段生命周期onPause / onResume中进行它可能会很棒,但它没有用(app崩溃)。 这是logcat:
05-25 09:15:27.315 4964-4964/com.example.j1oden.exkotlin E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.j1oden.exkotlin, PID: 4964
java.lang.IllegalStateException: btnPrev must not be null
现在我正在尝试使用“fragmentManager.findFragmentByTag”但是如果我的片段总是被加载的话,它总是返回true(我在这里想念一些东西)。
在这里,您可以看到我如何设法将片段加载到我的FrameLayout中:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Init Buttons OnClickListener
btnFrag.setOnClickListener { onClick(btnFrag) }
btnPrev.setOnClickListener { onClick(btnPrev) }
btnNext.setOnClickListener { onClick(btnNext) }
btnWeb.setOnClickListener { onClick(btnWeb) }
Log.d("oncreate", "MA_oncreate")
}
@Suppress("CAST_NEVER_SUCCEEDS")
// OnClick Buttons Fragments Redirection Links
fun onClick(v: View?) {
when (v?.id) {
R.id.btnFrag -> {if (isFrag1Loaded) showFrag2() else showFrag1()}
R.id.btnPrev -> {if (FragW.webview.canGoBack()) webview.goBack()
else Toast.makeText(baseContext, "No History Available", Toast.LENGTH_SHORT).show()}
R.id.btnNext -> {if (FragW.webview.canGoForward()) webview.goForward()
else Toast.makeText(baseContext, "No History Available", Toast.LENGTH_SHORT).show()}
R.id.btnWeb -> { showFragW() }
}
//isBtnEnabled = fragmentManager.findFragmentByTag("tagFragW") != null && fragmentManager.findFragmentByTag("tagFragW").isVisible
}
// Show Fragment 1 function
private fun showFrag1() {
val transaction = manager.beginTransaction()
transaction.replace(R.id.frag_container, Frag1(), "tagFrag1")
transaction.commit()
transaction.addToBackStack("tagFrag1")
isFrag1Loaded = true
}
// Show Fragment2 function
private fun showFrag2() {
val transaction = manager.beginTransaction()
transaction.replace(R.id.frag_container, Frag2(), "tagFrag2")
transaction.commit()
transaction.addToBackStack("tagFrag2")
isFrag1Loaded = false
}
// Show FragmentW function
private fun showFragW() {
val transaction = manager.beginTransaction()
transaction.replace(R.id.frag_container, FragW(), "tagFragW")
transaction.addToBackStack(null)
transaction.addToBackStack("tagFragW")
transaction.commit()
}
// WebView Custom Class
open class mWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request?.url.toString())
return true
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
}
感谢您的帮助!