I might be missing something very simple here, but I could definitely use some help.
I have an activity inside which I want to load different fragments with different content and different toolbar style (i.e. Toolbars with custom View and CollapsingToolbarLayout(that too having custom layout inside in it)). At the same time, I want to have one instance of the drawer, accessible through the single activity(i.e. MainActivity).
I have gone through the examples to find something similar, but all of them use new activities in order to populate their content or they just hide/show toolbar content that is not appropriate in my case as I've custom Toolbar views for each Fragment, therefore I cannot find out what should be the order of the layout views. Some of the solution that I've gone through are like :
Collapsing Toolbar only for one Fragment in Navigation View
Coordinator Layout with Toolbar in Fragments or Activity
Collapsing Toolbar and DrawerLayout
TL;DR
For one Fragment I want Toolbar as below
And for other Fragment
EDIT:
This is not a clean code but it is a working one. I just want to show you. You can use something like BaseFragment and structure a better code. In MainFragment you can use navigation drawer and in DetailFragment you can use back arrow on toolbar. If you want you can use navigation view in DetailFragment too. Also you can use collapsing toolbar in any fragment which you prefer.
MainActivity
class MainActivity : AppCompatActivity() {
private var actionBarToggle : ActionBarDrawerToggle? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setUpNavigationList()
if (savedInstanceState == null){
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_container, MainFragment())
.addToBackStack(null)
.commit()
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item!!.itemId){
android.R.id.home -> onBackPressed()
}
return true
}
fun setActionBarDrawerToggle(toolbar: Toolbar){
actionBarToggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.drawer_open, R.string.drawer_close)
actionBarToggle?.syncState()
drawer_layout.closeDrawer(Gravity.START)
}
fun lockDrawer(lock: Boolean){
val lockMode = if (lock) DrawerLayout.LOCK_MODE_LOCKED_CLOSED else DrawerLayout.LOCK_MODE_UNLOCKED
drawer_layout.setDrawerLockMode(lockMode)
actionBarToggle?.isDrawerIndicatorEnabled = lock
}
private fun setUpNavigationList(){
val items = arrayListOf("Detail Fragment")
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
list_navigation.adapter = adapter
list_navigation.setOnItemClickListener { parent, view, position, id ->
when (position){
0 -> {
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_container, DetailFragment())
.addToBackStack(null)
.commit()
}
}
drawer_layout.closeDrawer(Gravity.START)
}
}
}
MainFragment
class MainFragment() : Fragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_main, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity as AppCompatActivity).setSupportActionBar(toolbar_detail)
(activity as MainActivity).lockDrawer(false)
(activity as MainActivity).setActionBarDrawerToggle(toolbar_main)
}
}
DetailFragment
class DetailFragment() : Fragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_detail, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity as MainActivity).setSupportActionBar(toolbar_detail)
(activity as MainActivity).lockDrawer(true)
(activity as MainActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
}
Main Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.coskun.drawer.MainActivity">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/list_navigation"
android:layout_width="150dp"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:layout_gravity="start"/>
</android.support.v4.widget.DrawerLayout>
MainFragment Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.coskun.drawer.DetailFragment">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_main"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="#color/colorPrimary"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_fragment"/>
</LinearLayout>
DetailFragment Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.coskun.drawer.DetailFragment">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_detail"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="#color/colorAccent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/detail_fragment"/>
</LinearLayout>
PREVIOUS ANSWER:
You can define navigation drawer logic in activity and you can use separate toolbars for each fragment. You just need to sync state navigation drawer state with fragment toolbars.
fun setActionBarDrawerToggle(toolbar: Toolbar){
actionBarToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close)
actionBarToggle?.syncState()
drawerLayout.closeDrawer(Gravity.START)
}
fun lockDrawer(lock: Boolean){
val lockMode = if (lock) DrawerLayout.LOCK_MODE_LOCKED_CLOSED else DrawerLayout.LOCK_MODE_UNLOCKED
drawerLayout.setDrawerLockMode(lockMode)
actionBarToggle?.isDrawerIndicatorEnabled = lock
}
You can take a look at this code. I set toolbar as action bar in every fragment and let them to inflate their own menu and sync with activities drawer state. Let me know if this helps.
Related
This is supposedly a simple thing to achieve but for some reason I can't get it to work. I'm using SDK 30 emulator to test. Basically the new fragment appears but there is zero animation whatsoever. If I add a Fade() transition it works only for the fade transition. I've tried setting sharedElement callback but the methods are called only intermittently. Basically it's a simple image. You click on it and the new fragment appears. Click it again and it's gone.
Layout snippet of activity containing image
<FrameLayout
android:id="#+id/container_test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
>
<ImageView
android:id="#+id/image_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_error_24"
android:transitionName="image"
android:layout_gravity="center"
/>
</FrameLayout>
Logic to open image fragment
override fun openImageFragment(imageView: ImageView) {
val fragment = ImageFragment()
fragment.image = imageView.drawable
fragment.arguments = Bundle().also {
it.putString(ImageFragment.KEY_TRANSITION, imageView.transitionName)
}
// fragment.enterTransition = Fade()
// fragment.exitTransition = Fade()
supportFragmentManager
.beginTransaction()
.setReorderingAllowed(true)
.addSharedElement(imageView, imageView.transitionName)
.replace(R.id.container_test, fragment)
.commitNow()
}
Image fragment layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
/>
</FrameLayout>
ImageFragment
class ImageFragment : Fragment() {
private lateinit var binding: FragmentImageBinding
var image: Drawable?= null
companion object {
const val KEY_TRANSITION = "TRANSITION"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val transition = TransitionInflater.from(requireContext()).inflateTransition(android.R.transition.move)
sharedElementEnterTransition = transition
sharedElementReturnTransition = transition
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentImageBinding.inflate(inflater, container, false)
binding.imageView.transitionName = arguments?.getString(KEY_TRANSITION)
binding.imageView.setImageDrawable(image)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.setOnClickListener {
requireActivity().supportFragmentManager
.beginTransaction()
.remove(this)
.commit()
}
}
}
After much trial and error, I figured out the reason.
My initial fragment was placed statically on the XML, which prevented the fragment manager from replacing it. By using the layout inspector I figured out that the new fragment was placed right below the first one.
Basically the solution is to add the first fragment programmatically so the fragment manager can manipulate it.
I'm having some trouble to add options menu on a single fragment because it's breaking the navigation Up. Here my code
I have an single Activity with NoActionBar style and with this layout
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:fitsSystemWindows="true"
tools:context=".ui.MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<fragment
android:id="#+id/mainNavigationFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/main_graph" />
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbarLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="top">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:labelVisibilityMode="labeled"
app:menu="#menu/main_bottom_nav" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
in activity onCreate I make this setup for navigation
private fun setupNavigation() {
val navController = findNavController(R.id.mainNavigationFragment)
//each fragment of botton nav
val appBarConfiguration = AppBarConfiguration(setOf(
R.id.actionSchedule,
R.id.actionPayment,
R.id.actionNotification,
R.id.actionAccount))
toolbar.setupWithNavController(navController, appBarConfiguration)
bottomNavigationView.setupWithNavController(navController)
}
override fun onSupportNavigateUp() =
findNavController(R.id.mainNavigationFragment).navigateUp()
on each botton nav fragment I have some destinations and everything work as expected.
Now I need to add an menu only on right most fragment of botton nav, then on this specific fragment I add setHasOptionsMenu(true) in onCreate and inflate menu in onCreateOptionsMenu, but the menu does not appear.
Then I add setSupportActionBar(toolbar) on activity onCreate.
Now the menu appear only on this fragment but it's broke all 'UP' (back arrow on toolbar) of any destination (the back arrow appears, but when i press nothing happens). If I remove setSupportActionBar(toolbar) of activity the UP work again but not the toolbar menu.
What I need to do to make the menu work only in one fragment without broke anything else?
Thanks
If you're using setSupportActionBar, you must use setupActionBarWithNavController(), not toolbar.setupWithNavController as per the documentation.
if using toolbar do this:
in Acitvity:
class MyActivity : AppCompatActivity() {
private var currentNavController: NavController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
currentNavController = findNavController(R.id.settingNavHost)
currentNavController?.let {
val appBarConfiguration = AppBarConfiguration
.Builder()
.setFallbackOnNavigateUpListener {
onBackPressed()
true
}.build()
setSupportActionBar(toolbar)
toolbar.setupWithNavController(it, appBarConfiguration)
}
}
}
and in fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.my_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_save) {
saveInfo()
}
return super.onOptionsItemSelected(item)
}
I am trying to create an App like Instagram as part of a project and I want to keep the bottom part of the app fixed with the different Image Buttons that takes you to different parts of the App like home, messages and other functionalities.
I am currently making my app in a Relative Layout and will be switching to Constraint Layout after I get my App properly developed
I want the bottom part of the App with the Image Buttons fixed when a user clicks one of those buttons and is taken to some other type of layout xml file
Looks like you are talking about Bottom navigation bars :
Bottom navigation bars display three to five destinations at the bottom of a screen. Each destination is represented by an icon and an optional text label. When a bottom navigation icon is tapped, the user is taken to the top-level navigation destination associated with that icon.
With the Bottom navigation bars, you can switch fragments and have the navigation bar visible and fixed all over your app.
You can find a lot of information about how to create this, you can check this toturial, this video and many more.
You can use Bottom Navigation View or even a TabLayout anchored at the bottom of an activity.
You need an Activity that will host Fragments. These fragments will be displayed in turn as you interact with the Activity's hosting view.
I have created an Android Project to demonstrate. Sorry, you didn't specify language so i wrote it in Kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupViewPager(pager)
}
//the ViewPager will be responsible for navigating through your fragments even when you need to slide through them
private fun setupViewPager(viewPager: ViewPager){
val adapter = ViewPagerAdapter(supportFragmentManager)
setTabs(adapter)
// viewPager.offscreenPageLimit = 3
viewPager.adapter = adapter
initTabLayout()
}
//assign icons to the TabLayout
#SuppressLint("NewApi")
fun setTabIcons(){
tabLayout.getTabAt(0)!!.setIcon(ContextCompat.getDrawable(applicationContext,R.mipmap.ic_launcher))
tabLayout.getTabAt(1)!!.setIcon(ContextCompat.getDrawable(applicationContext,R.mipmap.ic_launcher))
tabLayout.getTabAt(2)!!.setIcon(ContextCompat.getDrawable(applicationContext,R.mipmap.ic_launcher))
}
#SuppressLint("NewApi")
fun initTabLayout(){
tabLayout!!.setupWithViewPager(pager)
setTabIcons()
}
//assign Fragments associated with a specific Tab Item
private fun setTabs(adapter:ViewPagerAdapter){
adapter.addFragment(FragmentOne(), "")
adapter.addFragment(FragmentTwo(), "")
adapter.addFragment(FragmentThree(), "")
}
}
class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager){
private val mFragmentList = ArrayList<Fragment>()
private val mFragmentTitleList = ArrayList<String>()
override fun getItem(position: Int): Fragment {
return mFragmentList[position]
}
override fun getCount(): Int {
return mFragmentList.size
}
fun addFragment(fragment: Fragment, title: String){
mFragmentList.add(fragment)
mFragmentTitleList.add(title)
}
override fun getPageTitle(position:Int): CharSequence{
return mFragmentTitleList.get(position)
}
}
Your single fragment will look something like:
class FragmentOne : Fragment() {
lateinit var rootView:View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_view,container,false)
rootView.findViewById<TextView>(R.id.textView).setText("Fragment One")
return rootView
}
}
Your view will look something like this (in this case it is named fragment_view.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#FFF"
android:elevation="6dp"
android:layout_gravity="bottom"
app:tabGravity="center"
app:tabRippleColor="#color/colorAccent"
app:tabPaddingStart="35dp"
app:tabPaddingEnd="35dp"
app:tabBackground="#android:color/transparent"
app:tabTextColor="#color/colorPrimaryDark"
app:tabSelectedTextColor="#color/colorPrimaryDark"
app:tabIndicatorColor="#android:color/transparent"
android:minHeight="?attr/actionBarSize"
/>
I'm developing an Android app (I'm a newbie) that uses a Navigation Drawer. I've created multiple fragments that represent the various item in the side menu. One of them has a RecyclerView, and I want to show another fragment with various details when the user clicks one of the item of the RecyclerView.
I've created the structure successfully, implement the click listener on the RecyclerView item, but I don't know how to show the details fragment (and how to go back from it).
If showing another fragment is not the right way, please suggest me the best way to obtain the navigation that I need.
CODE
MenuActivity.xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:titleTextColor="#android:color/white"/>
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar"/>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
MenuActivity.kt
class MenuActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
val vendutoFragment = VendutoFragment()
val prezziFragment = PrezziFragment()
val giacenzeFragment = GiacenzeFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
navigationView.setNavigationItemSelectedListener(this)
if(savedInstanceState == null){
addFragment(vendutoFragment)
navigationView.setCheckedItem(nav_venduto)
}
}
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
var selectedFragment = Fragment()
when (item.itemId) {
R.id.nav_venduto -> {
selectedFragment = vendutoFragment
}
R.id.nav_prezzi -> {
selectedFragment = prezziFragment
}
R.id.nav_giacenze -> {
selectedFragment = giacenzeFragment
}
}
replaceFragment(selectedFragment)
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
private fun addFragment(fragment: Fragment){
supportFragmentManager.beginTransaction().add(R.id.frameLayout, fragment).commit()
}
private fun replaceFragment(fragment: Fragment){
supportFragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).commit()
}
}
1st Fragment with RecyclerView and clickable item
class GiacenzeFragment: Fragment(){
var global: Global? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.fragment_giacenze, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?)
{
super.onViewCreated(view, savedInstanceState)
//you can set the title for your toolbar here for different fragments different titles
activity!!.title = "Giacenze"
}
override fun onActivityCreated(savedInstanceState: Bundle?)
{
super.onActivityCreated(savedInstanceState)
giacenzeTable.layoutManager = LinearLayoutManager(context) as RecyclerView.LayoutManager?
global = getActivity()?.getApplication() as Global
// Access the RecyclerView Adapter and load the data into it
giacenzeTable.adapter = GiacenzeTableAdapter(global!!.prodotti, { prodotto: Prodotto -> prodottoItemClicked(prodotto) })
}
private fun prodottoItemClicked(prodotto: Prodotto)
{
Toast.makeText(context, "Clicked: ${prodotto.name}", Toast.LENGTH_SHORT).show()
var serbatoiFrag = SerbatoiFragment()
serbatoiFrag.idProdotto = prodotto.idProdotto
serbatoiFrag.nameProdotto = prodotto.name
fragmentManager?.beginTransaction()!!.replace(R.id.frameLayout, serbatoiFrag).commit()
}
}
if you want to load fragment in a new activity, just open new activity and use replaceFragment
if you want to load in same activity, just use replaceFragment
do you know how to use replaceFragment?
going crazy with implementing aciton bar to my fragment,whatever I do I can not add a "title" or a menu to my toolbar (I used the code that is generated in android studio when creating new project with "Navigation Drawe Activity and put it in fragment- for referance)this is how my fragment looks like:
class BaseFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
var appCompatActivity = activity as AppCompatActivity;
var view = inflater!!.inflate(R.layout.fragment_base, container, true);
var toolbar = view.findViewById<android.support.v7.widget.Toolbar>(R.id.toolbar)
toolbar.setTitle(R.string.e_mail)
appCompatActivity.setSupportActionBar(toolbar)
return inflater!!.inflate(R.layout.fragment_base, container, true)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.main, menu);
}
}
and my fragment_base:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
and the result is:
what am I doing wrong?
The way you set an action bar in the Fragment is a bad approach, because when the fragment is destroyed, that Action Bar will also be destroyed.
DrawerLayout on Action Bar is a sliding menu that appears on the android screen with a hamburger menu icon. You shouldn't destroy it on every fragment creation. You need to set Action Bar in your MainActivity.
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Set a Toolbar to replace the ActionBar.
val toolbar: Toolbar = findViewById<Toolbar>(R.id.toolbar)
toolbar.setTitle(R.string.e_mail)
setSupportActionBar(toolbar)
// Find our drawer view
val mDrawer: DrawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout);
}
}
It will solve your Action Bar title issue. Hope it helps!