我正在使用导航抽屉活动来开发Android应用程序。 每个不同的菜单项都用于在我的mainActivity上显示其自己的片段。
打开抽屉时,我想单击抽屉标题(对应于文件nav_header_main.xml,带有徽标和2个文本),然后显示我的HomeFragment()。
我该怎么做?
答案 0 :(得分:0)
我是新手,所以答案似乎很明显,但是好的,我终于找到了解决方法:
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
fun changeFragment (fragment: Fragment){
supportFragmentManager.beginTransaction().replace(R.id.content, fragment).commit()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
// hamburger menu listener
nav_view.setNavigationItemSelectedListener(this)
// navigation header menu listener
val headerLayout = nav_view.getHeaderView(0)
val nav_drawer_header = headerLayout.findViewById(R.id.nav_header) as LinearLayout
nav_drawer_header.setOnClickListener{
changeFragment(HomeFragment())
onBackPressed()
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}