当我已经在Kotlin中使用了不同布局的setContentView()时,如何在onCreate()函数中将谷歌广告加



有没有办法在onCreate((中有两个不同的setContentView((调用,或者有没有办法将它们分开?我已经使用setContentView((来加载我的导航抽屉和工具栏,我不知道如何重组代码以适应它也包括广告。

我是android开发的新手,所以我可能会错过一些非常琐碎的东西。

class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
lateinit var mAdView : AdView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
//Initialize fab listener and SnackBar onClick
val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Here goes Nothing!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)

appBarConfiguration = AppBarConfiguration(setOf(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow), drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
navView.setCheckedItem(R.id.nav_home)

MobileAds.initialize(this) {}
val adRequest = AdRequest.Builder().build()

//this is the line where I get an error
setContentView(R.layout.fragment_home)

mAdView = findViewById(R.id.adViewHomeFragment)
mAdView.loadAd(adRequest)

}
/**This creates the options menu**/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.navigation_drawer, menu)
return true
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}}

如果你对这个结构有什么问题或我如何改进它有任何建议,我将不胜感激。

//this is the line where I get an error
setContentView(R.layout.fragment_home)

不需要添加另一个布局来调用广告。使用setContentView()一次,在调用onCreate()之后您已经这样做了。确保您的adview已添加到xml布局文件中(在本例中为activity_main.xml(。从MainActivity调用它。查看此广告实现-横幅广告

如果你想在片段中广告,那么将adview添加到你的片段布局中,并从片段代码中调用它。您提供的代码不会加载片段。查看以下关于如何加载片段的示例-添加片段

最新更新