Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add TextView to Toolbar when I'm using the <include> tag?

So, I have a toolbar.xml file:

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"/>

And, I have an <include... tag in my layout:

<include
        layout="@layout/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/toolbar"/>

So I heard if I want to center the title of the activity on the toolbar, I simply need to add a TextVIew to the toolbar, like this:

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbarLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary">
    <TextView .../>
</android.support.v7.widget.Toolbar>

But, I'm using the include tag, and the text is apparently not showing up:

<include
            layout="@layout/toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:id="@+id/toolbar">

        <TextView
            android:text="@string/createNewOccasion"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView5"
            android:textSize="18sp"
            android:fontFamily="sans-serif-condensed"
            android:gravity="center"
            />
        </include>

So, what can I do to solve the problem? Here's how it's showing up: How it's showing up

If you want to see my full real layout, go here. Here's my activity if it is helpful in anyway: http://pastebin.com/g6ZXAxe5

like image 457
Ali Bdeir Avatar asked Jul 02 '16 22:07

Ali Bdeir


1 Answers

If you want to add a view to your Toolbar then you have to add it inside Toolbar as a child, and not a child of the include.

You already have this piece of code:

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbarLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary">
    <TextView 
        android:id="@+id/toolbarTextView"
        android:layout_width="20dp"
        android:layout_height="match_parent"             
        android:visibility="gone"/>
</android.support.v7.widget.Toolbar>

If you only want to show this TextView on one Activity then set TextView visibility to GONE by default and change it to VISIBLE inside your Activity where you want to show it.

You can get the TextView in any Activity where the above layout is included in the main layout.

TextView toolbarTextView = (TextView) findViewById(R.id.toolbarTextView);
like image 164
Sharj Avatar answered Sep 20 '22 13:09

Sharj