如何在Kotlin中加载片段?
我是新的kotlin我在我的应用程序中添加底部栏
val bottomNavigationView = findViewById<View>(R.id.navigation) as BottomNavigationView BottomNavigationViewHelper.removeShiftMode(bottomNavigationView) bottomNavigationView.setOnNavigationItemSelectedListener { item -> var selectedFragment: Fragment? = null when (item.itemId) { R.id.action_item1 -> selectedFragment = ItemOneFragment.newInstance() R.id.action_item2 -> selectedFragment = ItemTwoFragment.newInstance() R.id.action_item3 -> selectedFragment = ItemThreeFragment.newInstance() R.id.action_item4 -> selectedFragment = ItemThreeFragment.newInstance() } val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.frame_layout, selectedFragment) transaction.commit() true } //Manually displaying the first fragment - one time only val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.frame_layout, ItemOneFragment.newInstance()) transaction.commit()
ItemOneFragment.java
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ItemOneFragment extends Fragment { public static ItemOneFragment newInstance() { ItemOneFragment fragment = new ItemOneFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_item_one, container, false); }}
但我得到的错误:类型不匹配需要:在ItemOneFragment.newInstance()的片段我已经尝试了所有的东西在此先感谢。
它看起来像你在包含你的bottomNavigationView
代码的文件中导入android.app.Fragment
。 ItemOneFragment.newInstance()
返回与android.app.Fragment
不兼容的android.app.Fragment
。
更改导入到android.support.v4.app.Fragment
应该可以解决问题。