In-depth analysis of four Android components (9)-The combination of AppCompatActivity and toolbar of Activity

Source: Internet
Author: User

In-depth analysis of four Android components (9)-The combination of AppCompatActivity and toolbar of Activity

For technical blogs, we will always follow the latest API steps. Before API22, we used the title bar for processing in the ActionBarActivity Activity. After API22, Google abandoned ActionBarActivity, we recommend that you use AppCompatActivity.

However, the use of ActionBarActivity is similar to that of AppCompatActivity. Next we will introduce the use of AppCompatActivity, the latest Activity component.

The final result is basically the same as that shown in the figure below:

 

1. Preliminary Exploration of AppCompatActivity

We create a project in the default order of AndroidStudio. The default Activity inherits from AppCompatActivity. The Code is as follows:

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }}

Run the following interface:

 

The results are similar to those inherited from the Activity, which is ugly. Next, we will expand the title bar step by step to enrich his content.

2. AppCompatActivity and Toolbar

In fact, we do not need to use the title bar that comes with AppCompatActivity, so expansion will be very troublesome. In Android 5.0 in 14 years, Toolbar will be used to replace ActionBar, and ActionBarActivity will be replaced by AppCompatActivity, the Toolbar is introduced to the Activity.

(I) First, we must write a Toolbar in the configuration file. The Code is as follows:

<android.support.v7.widget.toolbar android:id="@+id/activity_main_toolbar" android:layout_height="wrap_content" android:layout_width="match_parent" android:minheight="?attr/actionBarSize" android:background="?attr/colorPrimary">    </android.support.v7.widget.toolbar>

① Android: minHeight = "? Attr/actionBarSize: sets the minimum height of the title bar to the height of the ActionBar.

② Android: background = "? Attr/colorPrimary ": the Dominant Color of the topic. That is, the default gray.

We know that android: theme = "@ style/AppTheme" is set in the application in the AndroidManifest. xml configuration file, and the following style is displayed in the AppTheme view.

<resources>    <!--{cke_protected}{C}%3C!%2D%2D%20Base%20application%20theme.%20%2D%2D%3E--><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">        <!--{cke_protected}{C}%3C!%2D%2D%20Customize%20your%20theme%20here.%20%2D%2D%3E--></style></resources>

We can see from the name that the default title bar is black. When toolbar is used, we must modify the Style File and remove the original title bar. The modified style file is as follows:

<resources>    <!--{cke_protected}{C}%3C!%2D%2D%20Base%20application%20theme.%20%2D%2D%3E--><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">        <!--{cke_protected}{C}%3C!%2D%2D%20Customize%20your%20theme%20here.%20%2D%2D%3E--></style></resources>

Run the following command at this time, so you will see that the interface does not have a title bar, because you have not set it to AppCompatActivity.

(Ii) display Toolbar to the interface

We create a method named initActionBar (). First of all, we obtain the ToolBar Control and set the Toolbar to Activity. The Code is as follows:

public void initActionBar() {    Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);    setSupportActionBar(toolbar);}

Run now and we will get the following interface:


 

Still not the expected effect. Next we will introduce the details of AppCompatActivity.

3. Detailed description of AppCompatActivity

(I) set title

We can see that our project name is always displayed in the title bar, which is obviously unsatisfactory for users. How to set the string of the title bar. We can add the following code before setsuppactionactionbar (toolbar:

SetTitle ("liyuanjinglylyj ");

This setTitle ("liyuanjinglyj") is the AppCompatActivity method, not the toolbar method. Then, run the program to obtain the following interface:

Then we will replace the setTitle of the AppCompatActivity with the setTitle of the Toolbar to see what the effect will be. In fact, the results are the same and there is no change.

You may want the title to be displayed in the middle. Unfortunately, the toolbar and AppCompatActivity do not provide relevant methods. However, you can add a TextView to the toolbar to configure its attributes, display it in the middle.

(Ii) set the rollback button

If my interface is not a main interface, but a sub-interface, I have a requirement to roll back to the previous interface, how can I set the icon on the left and implement the method. It is actually very simple. Add the following code to the setsuppactionactionbar (toolbar:

toolbar.setNavigationIcon(R.drawable.back);toolbar.setNavigationOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        finish();    }});

Why is it added to the setsuppactionactionbar (toolbar) instead of the front? You can add it to the front to try it. Although you can display the rollback image, the click event that does not call this button is not displayed, in the setsuppactionactionbar (toolbar), click Next to it to respond. Remember, otherwise the rollback will not work.

The running result is as follows:

(Iii) Set logo

It is not uncommon to set the logo in the title bar. For example, Netease sets the logo on the Netease APP homepage. In fact, the code is very simple and you only need a code. Add the following code before setsuppactionactionbar:

Toolbar. setLogo (R. id. app_logo );

The running result is as follows:

 

(Iv) set subtitle

Add the following code before setsuppactionactionbar (toolbar ::

Toolbar. setSubtitle ("liyuanjing ");

After running the interface, it is as follows:

(V) Set Menu

We know that onCreateOptionsMenu is the context menu. Similarly, you can directly set the menu in this method. The Code is as follows:

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    getMenuInflater().inflate(R.menu.menu_main, menu);    return  true;}

This method is the Activity method. As you have mentioned above that Toolbar is set to Activity, it will be displayed in the title bar by default. If you think this is not the case, you can add a statement, however, it does not matter if this statement is added or not.

Toolbar. setOnCreateContextMenuListener (this );

Run the program, as shown in:

4. Toolbar Style

3. the Toolbar under the title is blue and has a good Style. How can this be set? Although we focus on analyzing the Activity, we still need to mention the Style of the Activity title bar.

We will give a rough explanation of the styles used in the title bar above:

① # 00006ff : For example, the attribute set directly under the toolbar Control in the first step is the color of the toolbar.

② # 3A5FCD : The status bar color is the color above the title bar. I tested it with Xiaomi for 1 s, and its firmware does not implement its function very well, therefore, this system does not achieve its effect.

③ @ Android: color/white : The background color of the window, that is, the color of all places under the Activity title bar.

When we set three attributes, as shown above, the complete code is as follows:
 

<! -- Base application theme. --> <style name = "AppTheme" parent = "Theme. AppCompat. Light. NoActionBar"> <! -- Toolbar (actionbar) color --> <item name = "colorPrimary"> # 00006ff </item> <! -- Status Bar color --> <item name = "colorPrimaryDark"> # 3A5FCD </item> <! -- Background color of the window --> <item name = "android: windowBackground"> @ android: color/white </item> </style>
5. Toolbar menu style

Let's take a look at the effect of using the menu after the above CLICK:

Do you see that the pop-up APP menu blocks the title bar ?, No. If yes, you must have immediately uninstalled the application.

In the following task, the menu style is the same as that of other apps and is displayed under the title bar.

The parent class of the default toolbar style is Widget. appCompat. light. popupMenu. overflow, to change the pop-up style of the toobar menu, you must inherit the style of this parent class.

The Code is as follows:
 

<! -- Base application theme. --> <style name = "AppTheme" parent = "Theme. AppCompat. Light. NoActionBar"> <! -- Toolbar (actionbar) color --> <item name = "colorPrimary"> # 00006ff </item> <! -- Status Bar color --> <item name = "colorPrimaryDark"> # 3A5FCD </item> <! -- Background color of the window --> <item name = "android: windowBackground"> @ android: color/white </item> <item name = "actionOverflowMenuStyle"> @ style/LYJMenuStyle </item> </style> <style name = "LYJMenuStyle" parent = "@ style/ widget. appCompat. light. popupMenu. overflow "> <item name =" overlapAnchor "> false </item> </style>

Set this attribute so that the pop-up style will not overwrite the title bar like other apps.

Other attributes are briefly described here:

① ? Attr/colorPrimary : The pop-up menu background color is the title bar background color

② 0dip : Vertical spacing between the pop-up menu and the title bar

Add the two to LYJMenuStyle to implement the pop-up menu shown in:

 

Finally, we will introduce several important attributes in the menu:

App: showAsAction has three values:

Always: always displayed on the Interface
Never: not displayed on the interface. It is displayed only in the three dots on the right.
IfRoom: if there is a position to display, otherwise it will appear in the three dots on the right

You can use | both the preceding values are used.

The system also provides the default share menu and query menu for the menu. The Code is as follows:

App: actionViewClass = "android. support. v7.widget. SearchView"

App: actionProviderClass = "android. support. v7.widget. ?actionprovider"

The name must not be explained too much. The last one is the display priority, that is, the display order. Who is at the beginning and who is at the end:

Android: the smaller the orderInCategory value, the higher the display speed and the highest priority.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.