androidtitlebarcustom-titlebar

Set title text on custom title bar


I have to create a custom title bar, to set a dynamic text. This would be something like setting a Title, and below, the dynamic subtitle on the Actionbar.

In this case, the App title goes on the left side, as for default. The dynamic text goes in the right side, and must change dynamically.

This is the layout custom_titlebar.xml

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:orientation="vertical" >

<TextView 
    android:id="@+id/title_left_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="left" />

<TextView 
    android:id="@+id/title_right_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="right"
    android:layout_alignParentRight="true" />    
</RelativeLayout>

In the manifest I've defined:

<application
    android:theme="@style/Theme.NoTitle" >

And on the Activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        //HAVE COMENTED THIS, BECAUSE IT THROWS: You cannot combine custom titles with other title feature..

    setContentView(R.layout.main);

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);

    TextView title = (TextView) findViewById(R.id.title_left_text);
    title.setText(getTitle());

To change text dynamically, I also have on the Activity:

public void setTitleStatus(String right) {
    if (right.length() > 20) {
        right = right.substring(0, 20);
    }
    TextView status = (TextView) findViewById(R.id.title_right_text);

    status.setText(right);
}

The problem is that is throwing a NPE on the line of the onCreate where I set the title (title.setText(getTitle());)


Solution

  • change

    title.setText(getTitle().toString());