Alimov Shohrukh Alimov Shohrukh - 3 months ago 10
Android Question

Toolbar title in Fragments

How can i change Textview inside Toolbar when Fragments are changed? My toolbar is in a BaseActivity, so i could use in all activities.

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="4dp"
android:layout_marginLeft="20dp"
ndroid:layout_marginRight="attr/actionBarSize"
android:layout_marginTop="4dp"
android:textColor="@color/colorAccent2"
android:textSize="19sp"
tools:ignore="HardcodedText" />


</FrameLayout>
</android.support.v7.widget.Toolbar>

Answer

You could easily change title using this line:

((MyAppCompatBaseActivity)getActivity()).getSupportActionBar().setTitle("Hello World!");

Edit:

I just saw that you have a TextView inside your Toolbar. So to set the title do this in your BaseActivity:

public class BaseActivity extends AppCompatActivity {

    TextView textViewTitle;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Other Code
        textViewTitle = (TextView) findViewById(R.id.toolbar_title);
    }

    public void setTitle(String title) {
        textViewTitle.setText(title);
    }

}

Then in your Fragment just do this:

((BaseActivity)getActivity()).setTitle("Hello World!");
Comments