3

我正在尝试从 Android 架构组件实现Nagivation 。我能够成功地浏览我的片段。我正在尝试将它附加到我的底部导航,但我无法正确使用它。我可以在片段之间成功导航,Navigation.findNavController(View).navigate(R.id.Fragment)但是当我使用任何 UI 组件或后退按钮进行导航时,底部导航的突出显示不会改变,如下面的 gif 所示

在此处输入图像描述

我的代码如下MainActivity.kt

class MainActivity : AppCompatActivity() {


    private lateinit var navController: NavController


    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                navController.navigate(R.id.homeFragment)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                navController.navigate(R.id.addEmotionFragment)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        navController = Navigation.findNavController(this, R.id.nav_host)
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }


}

为了HomeFragment.kt

class HomeFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        button.setOnClickListener {
            Navigation.findNavController(it).navigate(R.id.addEmotionFragment)
        }
    }
}
4

2 回答 2

9

尝试使用导航-ui。

implementation 'androidx.navigation:navigation-ui:' + navigationVersion //currently 1.0.0-alpha05

在活动中

    navController = Navigation.findNavController(this, R.id.nav_host)
    NavigationUI.setupWithNavController(bottomNavigation, navController)

并确保您的片段 ID 匹配菜单 ID。

<item
        android:id="@+id/homeFragment"
        android:title="Home"/>
于 2018-08-28T13:20:17.663 回答
1

您需要在按钮单击中手动设置选中的属性,例如:

    button.setOnClickListener {
        Navigation.findNavController(it).navigate(R.id.addEmotionFragment)
        .... (Over Here)
    }

Java 代码将是:

MenuItem menuItem = YourBottomViewObject.getMenu().getItem(1); menuItemsetChecked(true); MenuItem menuItem = YourBottomViewObject.getMenu().getItem(0); menuItemsetChecked(false);

于 2018-08-19T06:48:50.503 回答