Hi guys, Recently in my android projects i used toolbar alot. And most common use i found was showing a title with a back button at the top in the toolbar. Well i used both in Fragments and Activities. So how we can create a simple toolbar is as follows :
1. MainActivity
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TextView tvTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setToolBar();
}
private void setToolBar() {
toolbar=(Toolbar)findViewById(R.id.toolbar);
tvTitle=(TextView)findViewById(R.id.tv_title);
tvTitle.setText("Toolbar Title");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
2. activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
layout="@layout/toolbar"/>
<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
3. toolbar.xml<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ToolBarTheme">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?attr/actionBarSize"
android:layout_marginRight="?attr/actionBarSize"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="@android:color/black" />
</android.support.v7.widget.Toolbar>
</LinearLayout>
4. style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
<style name="ToolBarTheme" parent="Base.ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">#000000</item>
<item name="android:textColorSecondary">#ffffff</item>
</style>
</resources>
Github Link :- https://github.com/CammyKamal/BlogTutorials/tree/master/AddingToolbar

No comments:
Post a Comment