For the More Curious: Accessing the AppCompat App Bar

As you saw in this chapter, you can change the contents of the app bar by adding menu items. You can also change other attributes of the app bar at runtime, such as the title it displays.

To access the AppCompat app bar, you reference your AppCompatActivity’s supportFragmentManager property. From CrimeFragment, it would look something like this:

    val appCompatActivity = activity as AppCompatActivity
    val appBar = appCompatActivity.supportActionBar as Toolbar

The activity that is hosting the fragment is cast to an AppCompatActivity. Recall that because CriminalIntent uses the AppCompat library, you made your MainActivity a subclass of AppCompatActivity, which allows you to access the app bar.

Casting supportActionBar to a Toolbar allows you to call any Toolbar functions. (Remember, AppCompat uses a Toolbar to implement the app bar. But it used to use an ActionBar, as you just read, hence the somewhat-confusing name of the property to access the app bar).

Once you have a reference to the app bar, you can apply changes like so:

     appBar.setTitle(R.string.some_cool_title)

See the Toolbar API reference page for a list of other functions you can apply to alter the app bar (assuming your app bar is a Toolbar) at developer.android.com/​reference/​androidx/​appcompat/​widget/​Toolbar.

Note that if you need to alter the contents of the app bar’s menu while the activity is still displayed, you can trigger the onCreateOptionsMenu(Menu, MenuInflater) callback by calling the invalidateOptionsMenu() function. You can change the contents of the menu programmatically in the onCreateOptionsMenu callback, and those changes will appear once the callback is complete.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.160.156