Continue previous tutorial
Step 1:
Go to build.gradle file add this dependency:
compile 'com.android.support:design:25.2.0'
Step 2:
Go to styles.xml file add this two line of code
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
Step 3:
Go to the res > layout folder create toolbar_normal.xml file and put this code inside the file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
Step 4:
Go to the res > menu folder create menu_main.xml file and put this code inside the file
<?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/action"
android:title="Testing"
app:showAsAction="always"/>
</menu>
Step 5:
You can implement the toolbar in your layout file like this already
<include layout="@layout/toolbar_normal"/>
Step 6:
Go to your java file and implement this two override methods
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: onBackPressed();
break; case R.id.action: break;
}
return super.onOptionsItemSelected(item);
}
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: onBackPressed();
break; case R.id.action: break;
}
return super.onOptionsItemSelected(item);
}
Next go in to the onCreate method write this code
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Output:
Reminder: the title label can be set in the AndroidManifest file with the activity label.
Extra:
No comments:
Post a Comment