我是kotlin的新手,我想在kotlin中创建以下代码:
Fragment fragment = null;
switch(id) {
case R.id.nav_new:
fragment = new FragAllPosts();
break;
case R.id.nav_about:
fragment = new FragAuthors();
break;
case R.id.nav_tags:
fragment = new FragTags();
break;
}
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
这些片段非常基础,但还没有包含任何参数。 如何在kotlin中实现上述目标?谢谢!
答案 0 :(得分:5)
您可以将以下代码段作为示例:
var fragment: Fragment? = null
when(id) {
R.id.nav_new -> fragment = FragAllPosts()
R.id.nav_about -> fragment = FragAuthors()
R.id.nav_tags -> fragment = FragTags()
}
if(null != fragment) {
val ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
答案 1 :(得分:1)
希望有帮助!
var fragment: Fragment? = null
when (id) {
R.id.nav_new -> fragment = FragAllPosts.newInstance()
R.id.nav_about -> fragment = FragAuthors.newInstance()
R.id.nav_tags -> fragment = FragTags.newInstance()
}
// activity use supportFragmentManager
// fragment use childFragmentManager
fragment?.apply {
supportFragmentManager?.beginTransaction()?.replace(R.id.content_frame, this)?.commit()
}
// Example class fragment create newInstance function
class FragAllPosts : Fragment() {
companion object {
fun newInstance(bundle: Bundle? = null): FragAllPosts = FragAllPosts().apply {
arguments = bundle
}
}
}