Toolbar Android

  • Toolbar is a view introduced in Android Lollipop(API 21) the spiritual successor of the ActionBar(Actionbar is replaced with Toolbar)
  • Appearance and behavior can be more easily customized than the ActionBar.
  • Works well with app’s targeted to API 21 and above.
  • Android has updated the AppCompat support libraries so the Toolbar can be used on lower Android OS devices as well.

Toolbar Advantages

  • Toolbar is a View included in a layout like any other View
  • As a regular View, the toolbar is easier to position, animate and control

Using Toolbar as Action-Bar

  • To use Toolbar as an ActionBar, first ensure the AppCompat-v7 support library is added to your application

build.gradle (Module:app) file

dependencies {
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
}
  • disable the theme-provided ActionBar

res/styles.xml file:

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="
Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
  • Now add a Toolbar to your Activity in layout file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"><android.support.v7.widget.Toolbar
android:id="@+id/tb_toolbarmain"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimaryDark">
</android.support.v7.widget.Toolbar>

<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="@drawable/toolbar_dropshadow" />
</LinearLayout>
  • Activity.java
public class ToolbarMainActivity extends AppCompatActivity {

private Toolbar tbtoolbarmain;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toolbar_main);
initViews();
}

private void initViews() {
//find the toolbar view from layout
tbtoolbarmain = (Toolbar) findViewById(R.id.tb_toolbarmain);
//set the toolbar view as actionbar for app
setSupportActionBar(tbtoolbarmain);
//Enabling the Navigation icon in toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Title of the toolbar
getSupportActionBar().setTitle("Title");
//subtitle of the toolbar
getSupportActionBar().setSubtitle("Sub Title");
LinearLayout.LayoutParams layoutParams
= (LinearLayout.LayoutParams) tbtoolbarmain.getLayoutParams();
// layoutParams.height = Toolbar.LayoutParams.MATCH_PARENT;
tbtoolbarmain.setLayoutParams(layoutParams);

}
}
Toolbar output in device
if you like this tutorial be sure to follow me on medium recommend this tutorial to others