Home > Enterprise >  Main menu lags and renders twice in fragment
Main menu lags and renders twice in fragment

Time:09-27

How to fix stuttering while clicking on main menu in fragment. It also renders main menu twice. I'm using custom toolbar and calling this on fragment.

Attaching code and video for reference.

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    } 
   override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) :Boolean {
      inflater.inflate(R.menu.main_menu,menu)
      return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
             R.id.about -> {
                 Log.d("MainFragment","About")
                 true
             }

            R.id.starred -> {
                Log.d("MainFragment","Starred")
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

enter image description here

CodePudding user response:

I think that there's not enough information provided to come up with a good answer. Based on the video it looks like there might be some logic reloading your fragment/activity a bunch of times which could cause the lag.

I'd recommend setting a breakpoint in the code where the menu is inflated and seeing if it is hit a bunch of times. Could also try setting one in the view somewhere and see if it's getting reloaded a ton.

CodePudding user response:

I have checked your onCreateOptionsMenu(menu: Menu?): Boolean signature and it doesn't seem right.

First of all it shouldn't return a Boolean which makes me think you are writing this code inside an AppCompatActivity() instead of a Fragment() Class.

You need to move your code from the Activity Class to the Fragment Class instead and use this method to inflate your menu.

 override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
       inflater.inflate(R.menu.main_menu,menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

Instead of returning a Boolean, do call the super class' onCreateOptionsMenu i.e. super.onCreateOptionsMenu(menu, inflater).

Be sure to call setHasOptionsMenu(true) to show the menu preferrably inside the Fragment's onCreateView() method.

  • Related