Search code examples
androidandroid-fragmentsandroid-toolbar

Access toolbar textview from Fragment in android


I have navigation drawer with custom toolbar. I am trying to access textView in toolbar in Fragment and set a text in fragment. Is this possible, if so how?

Here is the toolbar.xml I have:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/tools"
 android:id="@+id/toolbar"
 style="@style/ActionBar"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/backgroundcolor"
 android:minHeight="?attr/actionBarSize"
 app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/relativeLayoutID">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|center"
        android:layout_centerVertical="true"
        android:text="@string/register_title"
        android:textColor="@color/blackText"
        android:textSize="@dimen/text_size_medium" />

    <ImageView
        android:id="@+id/action_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_gravity="right|center"
        android:contentDescription="@string/logo"
        android:paddingRight="5dp"
        android:src="@drawable/logoactionbar" />
</RelativeLayout>

I want to set toolbar_title's text according to fargment I have clicked. How do I access them in Fragment.

Let me know!

Thanks!


Solution

  • Please try this one

    toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    textToolHeader = (TextView) toolbar.findViewById(R.id.textToolHeader);
    textToolHeader.setText("Text which you want");
    

    Hope this will helpful for you.