Introduction to Toolbar Toolbar is a new control introduced in Android 5.0. Before Toolbar appeared, we often used ActionBar and ActionActivity to implement the top navigation bar. Therefore, Toolbar can be understood as an upgraded version of ActionBar. Toolbar greatly expands ActionBar and is more flexible to use. Unlike ActionBar, Toolbar is more like a general View element. It can be placed anywhere in the view tree system, can be animated, can scroll with scrollView, and can interact with other views in the layout. Basic Use of Toolbar 1. To use Toolbar, you should first add the V7 compatible package to the Gradle configuration script (the code is as follows, the version is the version when Nanmei wrote this article), or use the operation method of the graphical interface of Android Studio to depend on the V7 compatible package. - compile 'com.android.support:appcompat-v7:23.1.1'
2. Add Toolbar to the layout file where we need the top navigation bar, and configure some common properties (when using custom properties, be sure to add the namespace "app" to the root node). - xmlns:app= "http://schemas.android.com/apk/res-auto"
Here we only list some commonly used attributes, such as minimum height, back button icon, background, etc. It should be noted that the "?" in the attribute value indicates that the Android system theme style is reused. This means that if we change the colorPrimary attribute in the theme style, the background color of the Toolbar will also change, so we are reminded to make some configurations in the theme style. - <android.support.v7.widget.Toolbar
- android:id= "@+id/toolbar"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:background= "?attr/colorPrimary"
- android:minHeight= "?actionBarSize"
- app:navigationIcon= "@mipmap/arrow_left"
- app:title= "title" />
3. Make some common configurations in the styles.xml file. Since we are using AppCompatActivity, so you must use the related themes of AppCompat. Here I use a bright theme without ActionBar. Note that you need to use your own theme in the manifest file. In order to completely remove the ActionBar, you need to write windowActionBar, windowNoTitle, and add the android declaration to ensure that the ActionBar that comes with the system and the third-party compatibility package are completely removed. - < style name = "AppTheme" parent = "Theme.AppCompat.Light.NoActionBar" >
- < item name = "colorPrimary" > @color/red </ item >
- < item name = "colorPrimaryDark" > @color/green </ item >
- < item name = "colorAccent" > @color/blue </ item >
- < item name = "android:textColorPrimary" > @color/white </ item >
-
- < item name = "android:windowActionBar" > false </ item >
- < item name = "android:windowNoTitle" > true </ item >
-
- < item name = "windowActionBar" > false </ item >
- < item name = "windowNoTitle" > true </ item >
- </ style >
4. The following is an explanation of several colors in the theme. Please refer to the pictures below for understanding. - colorPrimaryDark is the background color of the status bar at the top of our phone (changing it requires support from Android 5.0 and above phones).
- colorPrimary refers to the color of the navigation bar.
- colorAccent refers to the color of our commonly used controls such as Button.
- textColorPrimary refers to the color of the title in our navigation bar.
- WindowBackground refers to the default color of our window.
- navigationBarColor refers to the background color of the virtual buttons in Android phones.
5. Perform common operations on Toolbar in the code. After finding Toolbar by ID, you can listen to clicks on the navigation icon, provided that the navigation icon has been added in the layout file or Java code. The menu can also be used in the same way. Please refer to the comments for details. - Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
-
- //Monitor the navigation icon on the left side of the Toolbar
- toolbar.setNavigationOnClickListener(new View .OnClickListener() {
- @Override
- public void onClick( View v) {
- Toast.makeText(MainActivity.this, "return" , Toast.LENGTH_SHORT).show();
- }
- });
- //Use menu in Toolbar toolbar.inflateMenu(R.menu.menu_main);
- toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
- @Override
- public boolean onMenuItemClick(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.action_item1:
- Toast.makeText(MainActivity.this, "Menu 1" , Toast.LENGTH_SHORT).show();
- return true ;
- case R.id.action_item2:
- Toast.makeText(MainActivity.this, "Menu 2" , Toast.LENGTH_SHORT).show();
- return true ;
-
- case R.id.action_item3:
- Toast.makeText(MainActivity.this, "Menu 3" , Toast.LENGTH_SHORT).show();
- return true ;
- } return false ;
-
- }
- });
6. Operation effect diagram Toolbar Advanced Use - Customizing Toolbar From the comparison below, we can see that the native Toolbar screen is too beautiful to look at directly. Generally speaking, if we want to use Toolbar in a project, we should customize it. Let's start discussing how to customize Toolbar. Let me give you the core points: - Customize the layout and add it to the Toolbar
- Customize some properties when necessary
- The custom Class inherits Toolbar, reads custom properties, sets the layout and content of Toolbar, and finally needs to expose some functions to set titles, listeners, etc. The following steps are explained in detail.
1. Write a custom layout to put in the custom Toolbar. - <?xml version= "1.0" encoding= "utf-8" ?>
-
- <RelativeLayout
- xmlns:android= "http://schemas.android.com/apk/res/android"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- >
-
- <RelativeLayout
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:layout_marginLeft= "10dp"
- android:layout_marginRight= "10dp" >
-
- <ImageView
- android:id= "@+id/toolbar_leftButton"
- android:layout_width= "@dimen/icon_size"
- android:layout_height= "@dimen/icon_size"
- android:layout_alignParentLeft= "true"
- android:layout_centerVertical= "true"
- android:src= "@mipmap/icon_background"
- android:textColor= "@color/white"
- android:visibility= "visible"
- />
-
- <ImageView
- android:id= "@+id/toolbar_rightButton"
- android:layout_width= "@dimen/icon_size"
- android:layout_height= "@dimen/icon_size"
- android:layout_alignParentRight= "true"
- android:layout_centerVertical= "true"
- android:src= "@mipmap/icon_background"
- android:textColor= "@color/white"
- android:visibility= "visible"
- />
-
- <EditText
- android:id= "@+id/toolbar_searchview"
- style= "@style/search_view"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:layout_centerVertical= "true"
- android:layout_gravity= "center"
- android:layout_marginLeft= "10dp"
- android:layout_marginRight= "10dp"
- android:layout_toLeftOf= "@id/toolbar_rightButton"
- android:layout_toRightOf= "@id/toolbar_leftButton"
- android:drawableLeft= "@mipmap/icon_search"
- android:gravity= "center"
- android:hint= "Please enter the search content"
- android:visibility= "gone"
- />
-
- <TextView
- android:id= "@+id/toolbar_title"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:layout_centerInParent= "true"
- android:layout_gravity= "center"
- android:layout_marginLeft= "10dp"
- android:layout_marginRight= "10dp"
- android:layout_toLeftOf= "@id/toolbar_rightButton"
- android:layout_toRightOf= "@id/toolbar_leftButton"
- android:gravity= "center"
- android:textColor= "@color/white"
- android:textSize= "20sp"
- android:visibility= "gone"
- />
-
- </RelativeLayout>
-
- </RelativeLayout>
Let us explain it through the following two effect pictures O(∩_∩)O~~. Since it is generally not recommended to write attributes other than width and height in the outermost root node, I embedded a relative layout in the outermost relative layout and set the left and right margins. As for how to layout, it depends on the actual project. Nan's requirement here is that the title and search box can be switched at any time. Therefore, the title and search box are overlapped through the project layout, and when one of them is needed, the other is hidden. Another thing to note is that the left and right buttons should not be used by the Toolbar, because it may cause an asymmetric layout and make the title (search box) not centered. When the button is not in use, we do not hide it through the gone method, but use the @mipmap/icon_background blank image to take up space to keep the layout symmetrical. 2. Create a new attrs.mxl file in the values folder to store some custom attributes. These attributes can be understood by their literal meanings, so I won’t explain them in detail. - <?xml version= "1.0" encoding= "utf-8" ?>
- <resources>
- < declare -styleable name = "CNToolbar" >
- <attr name = "showSearchView" format = "boolean" />
- <attr name = "leftButtonIcon" format = "reference" />
- <attr name = "rightButtonIcon" format= "reference" />
- <attr name = "myTitle" format = "string" />
- </declare-styleable>
-
- </resources>
3. Customize the Class to inherit Toolbar. The main work of the code is to initialize the interface and listener, and open the interface for external operations. When initializing the interface, you need to read the value of the custom attribute through TintTypedArray, and then make some settings for the interface display. To initialize the listener, you need to use the callback of the interface. The specific steps are to publicly declare the interface, which has an onClick method; declare the implementation of the interface as a private member variable of the Toolbar; publicly declare the setListener method and assign the passed Listener implementation class to this member variable; call the onClick method of the member variable when necessary (such as calling it in the click event of the button on the left). Expose some functions, such as setting the title, setting whether to display the search box, title, etc. - /**
- * Customized navigation bar
- */ public class CNToolbar extends Toolbar {
- private TextView toolbar_title;
- private EditText toolbar_searchview;
- private ImageView toolbar_leftButton;
- private ImageView toolbar_rightButton;
- private View mChildView;
- private boolean showSearchView;
- private Drawable left_button_icon;
- private Drawable right_button_icon;
- private String title;
- public CNToolbar(Context context) {
- this(context, null , 0);
- } public CNToolbar(Context context, @Nullable AttributeSet attrs) {
- this(context, attrs, 0);
- } public CNToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr); //Get the values of some attributes in the layout file through code
- final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
- R.styleable.CNToolbar, defStyleAttr, 0);
- showSearchView = a.getBoolean(R.styleable.CNToolbar_showSearchView, false );
- left_button_icon = a.getDrawable(R.styleable.CNToolbar_leftButtonIcon);
- right_button_icon = a.getDrawable(R.styleable.CNToolbar_rightButtonIcon);
- title = a.getString(R.styleable.CNToolbar_myTitle);
- a.recycle(); //initial interface
- initView(); //Initial listener
- initListener();
- } /**
- * Initialize layout
- */
- private void initView() {
- if (mChildView == null ) {
- mChildView = View .inflate(getContext(), R.layout.toolbar, null );
-
- toolbar_title = (TextView) mChildView.findViewById(R.id.toolbar_title);
- toolbar_searchview = (EditText) mChildView.findViewById(R.id.toolbar_searchview);
- toolbar_leftButton = (ImageView) mChildView.findViewById(R.id.toolbar_leftButton);
- toolbar_rightButton = (ImageView) mChildView.findViewById(R.id.toolbar_rightButton);
- //Add a custom layout to the Toolbar
- addView(mChildView); //Set whether the title, search box, left and right buttons are displayed, and set the button icons
- if (showSearchView) {
- showSearchview();
- hideTitle();
- } else {
- hideSearchview();
- showTitle();
- if (title != null ) {
- toolbar_title.setText(title);
- }
- } if (left_button_icon != null ) {
- toolbar_leftButton.setImageDrawable(left_button_icon);
- } if (right_button_icon != null ) {
- toolbar_rightButton.setImageDrawable(right_button_icon);
- }
- }
-
- } /**
- * Rewrite the method to set the title
- *
- * @param title
- */
- @Override
- public void setTitle(CharSequence title) {
- toolbar_title.setText(title);
- } @Override
- public void setTitle(@StringRes int resId) {
- toolbar_title.setText(resId);
- } /**
- * Set the icons for the left and right buttons
- *
- * @param d
- */
- public void setLeftButtonIconDrawable(Drawable d) {
- toolbar_leftButton.setImageDrawable(d);
- } public void setRightButtonIconDrawable(Drawable d) {
- toolbar_rightButton.setImageDrawable(d);
- } /**
- * Switch between title and search box
- */
- public void setShowSearchView() {
- hideTitle();
- showSearchview();
- } public void setShowTitleView(String title) {
- hideSearchview();
- showTitle();
- toolbar_title.setText(title);
- } /**
- * Left and right button monitoring
- */
- private void initListener() {
- toolbar_leftButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick( View v) {
- if (onLeftButtonClickListener != null ) {
- onLeftButtonClickListener.onClick();
- }
- }
- });
-
- toolbar_rightButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick( View v) {
- if (onRightButtonClickListener != null ) {
- onRightButtonClickListener.onClick();
- }
- }
- });
- } public interface OnLeftButtonClickListener {
- void onClick();
- } public interface OnRightButtonClickListener {
- void onClick();
-
- } private OnLeftButtonClickListener onLeftButtonClickListener;
- private OnRightButtonClickListener onRightButtonClickListener;
- public void setOnLeftButtonClickListener(OnLeftButtonClickListener listener) {
- onLeftButtonClickListener = listener;
- } public void setOnRightButtonClickListener(OnRightButtonClickListener listener) {
- onRightButtonClickListener = listener;
- } /**
- * Set whether the title or search box is displayed
- */
- private void showTitle() {
- toolbar_title.setVisibility( View .VISIBLE);
- } private void hideTitle() {
- toolbar_title.setVisibility( View .GONE);
- } private void showSearchview() {
- toolbar_searchview.setVisibility( View .VISIBLE);
- } private void hideSearchview() {
- toolbar_searchview.setVisibility( View .GONE);
- }
- }
-
- 4. Use it like a general control where necessary. Pay attention to adding the namespace of the custom attribute, which is usually auto.
-
- <?xml version= "1.0" encoding= "utf-8" ?>
- <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
- xmlns:app= "http://schemas.android.com/apk/res-auto"
- android:layout_width= "match_parent"
- android:layout_height= "match_parent"
- android:orientation= "vertical" >
-
- <com.nan.cnshop.widget.CNToolbar
- android:id= "@+id/toolbar"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:background= "?attr/colorPrimary"
- android:minHeight= "?actionBarSize"
- app:leftButtonIcon= "@mipmap/icon_back_32px"
- app:showSearchView= "false"
- app:myTitle= "Home"
- />
-
- <WebView
- android:id= "@+id/webview"
- android:layout_width= "match_parent"
- android:layout_height= "match_parent"
- />
- </LinearLayout>
4. Use it like a general control where necessary. Pay attention to adding the namespace of the custom attribute, which is usually auto. - <?xml version= "1.0" encoding= "utf-8" ?>
- <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
- xmlns:app= "http://schemas.android.com/apk/res-auto"
- android:layout_width= "match_parent"
- android:layout_height= "match_parent"
- android:orientation= "vertical" >
-
- <com.nan.cnshop.widget.CNToolbar
- android:id= "@+id/toolbar"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:background= "?attr/colorPrimary"
- android:minHeight= "?actionBarSize"
- app:leftButtonIcon= "@mipmap/icon_back_32px"
- app:showSearchView= "false"
- app:myTitle= "Home"
- />
-
- <WebView
- android:id= "@+id/webview"
- android:layout_width= "match_parent"
- android:layout_height= "match_parent"
- />
- </LinearLayout>
It can also be used in the code, so I won’t go into details. - final CNToolbar toolbar = (CNToolbar) v.findViewById(R.id.toolbar);
-
- toolbar.setOnLeftButtonClickListener(new CNToolbar.OnLeftButtonClickListener() {
- @Override
- public void onClick() {
- toolbar.setShowSearchView();
- }
- });
|