我刚刚开始使用Fragments和ViewModels。我想替换Activity中的片段,该怎么做?
将Android和Fragments混合在一起的最佳方法是什么?
主活动
class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {
lateinit var drawerLayout: DrawerLayout
lateinit var fragmentTransaction: FragmentTransaction
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
drawerLayout= findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
val toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_open)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(setOf(
R.id.nav_home, R.id.nav_dersler, R.id.nav_soru,R.id.nav_socialmedia), drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
navView.setNavigationItemSelectedListener(this);
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.nav_home -> {
//Toast.makeText(this,"Anasayfa",Toast.LENGTH_SHORT).show()
}
R.id.nav_socialmedia -> {
Toast.makeText(this,"Sosyal Medya Hesaplarımızı Takip Edebilirsiniz",Toast.LENGTH_SHORT).show()
}
R.id.nav_dersler -> {
}
R.id.nav_soru -> {
}
}
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.action_refresh -> {
Toast.makeText(this,"Refreshing...",Toast.LENGTH_SHORT).show()
val refreshActivity = intent
finish()
startActivity(refreshActivity)
true
}
else -> super.onOptionsItemSelected(item)
}
return true
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
我有mobile_navigation.xml,但我不知道它是做什么的。谢谢你的帮助enter image description here
2条答案
按热度按时间5jdjgkvh1#
TL;DR:
Activity
是在应用中制作屏幕的基础组件。Fragment
是屏幕的一个动态部分,添加它是为了支持具有更大屏幕的平板电脑。我们通常以这些方式合并它们:
1.一个Activity作为容器,所有屏幕表示为
Fragment
s对于这种方法,您可以
自己实现它:
将片段添加到Activity堆栈:
替换Activity中的片段:
但是Android引入了Android导航组件来处理所有这些添加、替换和回栈处理:
我建议使用这种方法,因为它更容易。LINK
1.使用多个活动和片段
对于使用BottomNavigation、NavigationDrawer和...的每个屏幕使用带有多个Fragment的Activity来表示其中的每个选项卡。
一个很好的教程可以在这里找到。LINK
9njqaruj2#
类MainActivity:public void run(){