Tech tip of this week

Android: How to use Toolbar

Toolbar is a replacement to Android ActionBar. It has many features to customize its appearance unlike old ActionBar.

Toolbar is introduced in Android Lollipop, API level 21.
Google provides fully supported Toolbar features to lower android os devices via AppCompact support library.

In AppCompat, Toolbar is implemented in the android.support.v7.widget.Toolbar class.

Create Toolbar:

1. First of all, we need to disable ActionBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>

2. We have to add AppCompact library in build.gradle file
    compile "com.android.support:appcompat-v7:21.0.+"

3. Apply the theme to Activity.
   <activity android:name="com.example.sample.MyActivity"

      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
   </activity>

4. Add Toolbar in activity layout
   <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:minHeight="?attr/actionBarSize"

            android:background="#000000"
            android:layout_width="match_parent"

            android:layout_height="wrap_content" >                                                </android.support.v7.widget.Toolbar>

5. You just need to instantiate the Toolbar and add it to your activity by using         setSupportActionBar(Toolbar) method.

    import android.support.v7.app.ActionBarActivity;
    import android.support.v7.widget.Toolbar;
    public class MyActivity extends ActioBarActivity {
       @Override
        protected void onCreate(Bundle savedInstanceState)
        { 

           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

           setSupportActionBar(toolbar);
        }
    }

No comments:

Post a Comment