Search code examples
javaandroiduser-interfaceandroid-activityandroid-titlebar

Creating Custom Action bars for each activity


I need to create custom title bars for each and every Screen in my android application. For an example, in GMail, Yahoo Mail android applications, have you noticed that their title bar differs from activity to activity? This is what I need.

I went through number of tutorials, unfortunatly, they are to replace the title bar of the entire application with one custom title bar.

Following is what I have tried

Cuatom_title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

     <TextView
        android:id="@+id/bileeta_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="@string/_title"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#579bef"
        android:textSize="50sp" />

    <EditText
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_gravity="right"
        android:layout_marginRight="30dp"
        android:ems="10"
        android:hint="@string/search_hint"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

MainActivity.java

//Setting custom title bar
this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

setContentView(R.layout.activity_home);

//Set the custom title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);

But this just generated errors.

How can I create custom title bars for each and every activity?


Solution

  • in your onCreate()

     ActionBar actionBar = getActionBar();  //for higher version
     actionBar.setDisplayShowCustomEnabled(true);
     View customView=getLayoutInflater().inflate(R.layout.yourlayout, null);
     actionBar.setCustomView(customView);
    

    OR

     ActionBar actionBar = getSupportActionBar();  //to support lower version too
     actionBar.setDisplayShowCustomEnabled(true);
     View customView=getLayoutInflater().inflate(R.layout.yourlayout, null);
     actionBar.setCustomView(customView);