search
HomeJavajavaTutorialAndroid Basics: Use of Toolbar

Android Basics: Use of Toolbar

Nov 15, 2016 am 10:02 AM
android

Toolbar was launched in Android 5.0 and is used to replace the ActionBar control. It can be highly customized and flexible to use. The official ToolBar must be used in systems above 5.0. If you need to use it in a lower version, you need to use support v7 Toolbar in the package.

The next step is the introduction of the Toolbar on the official website:

Toolbar 
extends ViewGroup 
java.lang.Object 
   ↳    android.view.View 
       ↳    android.view.ViewGroup 
           ↳    android.support.v7.widget.Toolbar

Android Basics: Use of Toolbar

Prerequisites for use

To use the ToolBar, you need to hide the ActionBar of the activity. So how to hide it? There are three methods. The following introduces each

Method 1:

Modify in the res/values/styles.xml file

<style name="AppTheme.Base" parent="Theme.AppCompat"> 
 <item name="windowActionBar">false</item> 
 <item name="android:windowNoTitle">true</item> 
</style>

You can also directly use the theme without ActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

Method 2:

Modify the theme of the activity in the manifest file, as shown below:

<activity android:name="MainActivity" 
           android:theme="@style/Theme.AppCompat.Light.NoActionBar"> 
</activity>

Method 3 :

Cancel directly in the code. Before setContentView.

requestWindowFeature(Window.FEATURE_NO_TITLE); 
       setContentView(R.layout.activity_main); 
       //supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  在AppCompatActivity中

How to use

In the layout file. Add the following code. The position is not fixed.

<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar" 
    android:layout_width="match_parent" 
    android:layout_height="?android:attr/actionBarSize" 
    android:background="?attr/colorPrimaryDark" 
    app:title="Title" 
    app:titleTextColor="#222222" 
    app:logo="@mipmap/ic_launcher" 
    app:subtitle="subtitle"></android.support.v7.widget.Toolbar>

title is used to set the title. subtitle is used to set the subtitle. titleTextColor is used to set the title font color. background is used to set the background color. The effect is as follows:

Android Basics: Use of Toolbar

These values ​​can also be set dynamically in java code.

mToolbar.setTitle("JavaTitle"); 
       mToolbar.setSubtitle("JavaSubTitle"); 
       mToolbar.setLogo(R.mipmap.ic_launcher); 
       mToolbar.setNavigationIcon(android.R.drawable.ic_input_delete); 
       mToolbar.setOverflowIcon(ContextCompat.getDrawable(this, android.R.drawable.ic_menu_more)); 
/        setActionBar(mToolbar);  //activity中 
       setSupportActionBar(mToolbar);   //AppCompatActivity中

Add Menu

To add menu first we need to have menu, here I choose to create main.xml in res/menu/ to define the menu file. The code is as follows

<?xml version="1.0" encoding="utf-8"?> 
<menu xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:app="http://schemas.android.com/apk/res-auto"> 
    <item 
        android:id="@+id/add" 
        android:icon="@android:drawable/ic_menu_add" 
        android:title="Add" 
        app:showAsAction="never|withText"/> 
    <item 
        android:id="@+id/delete" 
        android:icon="@android:drawable/ic_menu_delete" 
        android:title="Delete" 
        app:showAsAction="never|withText"/> 
    <item 
        android:id="@+id/edit" 
        android:icon="@android:drawable/ic_menu_edit" 
        android:title="Edit" 
        app:showAsAction="never|withText"/> 
    <item 
        android:id="@+id/email" 
        android:icon="@android:drawable/sym_action_email" 
        android:title="Email" 
        app:showAsAction="never|withText"/> 
 
</menu>

The following is the code in the java file.

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
        getMenuInflater().inflate(R.menu.main, menu); 
        return true; 
    } 
 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) { 
            case android.R.id.home:  
                Toast.makeText(MainActivity.this, "您点击了NavigationIcon", Toast.LENGTH_SHORT).show(); 
                break; 
            case R.id.add: 
                Toast.makeText(MainActivity.this, "Add", Toast.LENGTH_SHORT).show(); 
                break; 
            case R.id.delete: 
                Toast.makeText(MainActivity.this, "Delete", Toast.LENGTH_SHORT).show(); 
                break; 
            case R.id.edit: 
                Toast.makeText(MainActivity.this, "Edit", Toast.LENGTH_SHORT).show(); 
                break; 
            case R.id.email: 
                Toast.makeText(MainActivity.this, "Email", Toast.LENGTH_SHORT).show(); 
                break; 
        } 
        return true; 
    }

Android Basics: Use of Toolbar

Show the Icon in the Menu

After writing this, we will find that the hidden menu does not display the icon, so how do we set it up:

Just need to re-do the method: The activity here is AppCompatActivity

@Override 
   protected boolean onPrepareOptionsPanel(View view, Menu menu) { 
       if (menu != null) { 
           if (menu.getClass() == MenuBuilder.class) { 
               try { 
                   Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE); 
                   m.setAccessible(true); 
                   m.invoke(menu, true); 
               } catch (Exception e) { 
                   Log.i("tag", "onPrepareOptionsPanel: " + 
                           getClass().getSimpleName() + 
                           "onMenuOpened...unable to set icons for overflow menu" 
                           + e); 
               } 
           } 
       } 
       return super.onPrepareOptionsPanel(view, menu); 
   }

The effect is as follows:

Android Basics: Use of Toolbar

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.