简体   繁体   中英

How do I access the default ToolBar from an Activity in Android?

I'm trying to access the default ToolBar from within and Activity's onCreateOptionsMenu function to change the Overflow menu icon (three dots icon). I want to use the setOverflowIcon method provided by this class.

I have read the official documentation, posts on StackOverflow and other websites and everything fails.

I tried for example Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); but I get an error that says that R.id.toolbar doesn't exist.

If you're using AppcompatActivity , you should use SupportActionBar like this:

supportActionBar?.title = "My Activity title"

this piece of code: Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); only works when you've added a Toolbar with toolbar id in xml . even if you did it, you should setSupportActionBar(yourToolBar) before doing anything. Then use supportActionBar directly instead.

you can get default toolbar from AppCompatActivity

getSupportActionBar();

Performing Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar) isn't expected to work because the ID does not explicitly exist. Every activity-Java class extends Activity (or its direct or indirect subclasses), you can use this to get the action bar (so to speak).

If your java file extends AppCompatActivity, you can use getSupportActionBar() to summon the ActionBar.

Java files that extend Activity require getActionBar() to summon the toolbar.

You can thereafter perform operations like changing the displayed text/title, background drawable, amongst other tasks.

To learn more about getting the action bar, check out this link .

聚会有点晚了,但默认工具栏可以通过像androidx.appcompat.R.id.action_bar这样的 id引用

findViewById(androidx.appcompat.R.id.action_bar)

create menu file using xml and place it in res/menu folder

onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.your_menu, menu);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM