Set a title in Toolbar from fragment in Android
Asked Answered
C

18

36

I have been using the latest Toolbar from AppCompatv7 lib.I have placed a textview in the ToolBar ViewGroup And I want to set a title into this Textview from the fragment in my activity.In case of a custom action bar ((ActionBarActivity)getActivity).setcustomView(..) would have done the job.But due to use of this ToolBar I am not able to use that.Also I have implemented a method in my BaseActivity that is inherited by all Activities.This BaseActivity contains my method to initialize a sliding drawer to the left.I have to initialize the initDrawerLayout() method in activity else the drawer would not be initialized.And if I initialize it in fragment its giving me all empty results,neither the toggle button for drawer and nor is the custom title getting set.

This is my initDrawer code..

public void initDrawerLayout(String toolbar_text) {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerRelative = (RelativeLayout) findViewById(R.id.drawer_relative);
        if (mDrawerLayout != null) {
            findViewById(R.id.drawer_btn_a).setOnClickListener(this);
            findViewById(R.id.drawer_btn_b).setOnClickListener(this);
            findViewById(R.id.drawer_btn_c).setOnClickListener(this);
            findViewById(R.id.drawer_btn_d).setOnClickListener(this);
            findViewById(R.id.drawer_btn_e).setOnClickListener(this);
            findViewById(R.id.drawer_btn_f).setOnClickListener(this);
            findViewById(R.id.drawer_btn_g).setOnClickListener(this);
            findViewById(R.id.drawer_btn_h).setOnClickListener(this);
            findViewById(R.id.drawer_btn_i).setOnClickListener(this);
            findViewById(R.id.drawer_btn_j).setOnClickListener(this);
            findViewById(R.id.drawer_btn_k).setOnClickListener(this);
            findViewById(R.id.drawer_btn_l).setOnClickListener(this);
            findViewById(R.id.my_layout).setOnClickListener(this);





            Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
            toolbar.setBackground(getResources().getDrawable(R.drawable.icn_actionbar_background));
            TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
            mTitle.setText(toolbar_text);
            mTitle.setTypeface(Typeface.DEFAULT_BOLD);
            if (toolbar != null) {
                setSupportActionBar(toolbar);
                 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
            toolbar.setNavigationIcon(R.drawable.ic_drawer);

             mDrawerToggle = new ActionBarDrawerToggle(
                    this,  mDrawerLayout, toolbar,
                    R.string.drawer_open, R.string.drawer_close
                );
                mDrawerLayout.setDrawerListener(mDrawerToggle);


            toolbar.setNavigationOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                        mDrawerLayout.closeDrawer(Gravity.LEFT);
                    } else {
                        mDrawerLayout.openDrawer(Gravity.LEFT);
                    }
                }
            });
            mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
                    GravityCompat.START);

            mDrawerLayout.setScrimColor(getResources().getColor(
                    android.R.color.transparent));
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);

        }
    }

And this my code in the fragment..

((FirstActivity) getActivity()).initDrawerLayout(mFirst.name); where mFirst is a object of class Person

and the toolbar code..

<android.support.v7.widget.Toolbar
            android:id="@+id/my_awesome_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize">
           <TextView
                android:id="@+id/toolbar_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:text="Toolbar Title"
                android:textColor="@color/action_text-color"
                android:textSize="18sp"
                android:textStyle="bold" /> 

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

Please help guys..

Clumsy answered 24/11, 2014 at 7:43 Comment(1)
The one who down voted this..can you please answer the question before downvoting..I have asked this question after quite a lot of searching.Clumsy
T
12

To allow a Fragment to communicate up to its Activity (to set your Toolbar Title), you can define an interface in the Fragment class and implement it within the Activity as described here: Communicating with Other Fragments.

Tear answered 5/12, 2014 at 8:22 Comment(0)
E
63

I do this like this: from the fragment call

getActivity().setTitle("your title");

But where you call it is important, because if each Fragment has it's own title, then one may override the other accidentally, which may be prevented like:

@Override
public void onResume() {
    super.onResume();

    Activity activity = getActivity();
    if (activity != null) {
        activity.setTitle(getString(R.string.my_title));
    }
}

For example, two Fragments of the same Pager can not be in resume-state at the same time.

Also you can "cast", to call any function of your parent Activity like this:

YourActivity mYourActiviy = (YourActivity) getActivity();
mYourActivity.yourActivityFunction(yourParameters);
Emanative answered 18/12, 2015 at 16:19 Comment(0)
H
28

In Kotlin.

In fragment:

(activity as YourActivity).supportActionBar?.title = getString(R.string.your_title)

In activity:

setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
Humoral answered 20/7, 2018 at 9:18 Comment(0)
L
15

If you have setSupportActionBar in Your Activity then you can easily change the toolbar title from your fragment

((YourActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
Litotes answered 14/3, 2018 at 6:19 Comment(0)
T
12

To allow a Fragment to communicate up to its Activity (to set your Toolbar Title), you can define an interface in the Fragment class and implement it within the Activity as described here: Communicating with Other Fragments.

Tear answered 5/12, 2014 at 8:22 Comment(0)
T
10

The answer is writen below in the oncreateview method of fragments.

getActivity().setTitle("your name");
Torray answered 8/8, 2016 at 14:15 Comment(0)
C
7

You can create Interface inside the Fragment. check below:-

public class MyFragment extends Fragment {
    OnMyFragmentListener mListener;

    // Where is this method called??
    public void setOnMyFragmentListener(OnMyFragmentListener listener) {
        this.mListener = listener;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnMyFragmentListener) {
            mListener = (OnMyFragmentListener) context;
            mListener.onChangeToolbarTitle("My Fragment"); // Call this in `onResume()`
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onResume(){
        super.onResume();
        mListener.onChangeToolbarTitle("My Fragment");
    }


    // This interface can be implemented by the Activity, parent Fragment,
    // or a separate test implementation.
    public interface OnMyFragmentListener {
        public void onChangeToolbarTitle(String title);
    }

}

In Activity:-

public class MyActivity extends AppCompatActivity implements MyFragment.OnMyFragmentListener {

    @Override
    public void onChangeToolbarTitle(String title){
        toolbar.setTitle(title);
    }

}

This works for me. :)

Coray answered 12/6, 2019 at 6:0 Comment(2)
Works very well except i'd recommend you just use onAttach(Context context) to initialize the listener and use onResume() to call the listener's methodsSchopenhauer
it shouldnt be hardly or complex like thatMonomial
B
5

This has worked for me, in Kotlin. Put this in your fragment class:

if (activity != null) {
        (activity as MainActivity).supportActionBar?.title = getString(R.string.action_history)
    }
Bangup answered 24/9, 2020 at 20:52 Comment(0)
K
4

If somebody struggles with this problem, this may be useful.

Basically you have 4 options, how to handle that:

  • use an interface in order to communicate with your activity, or any other convenient method, like an event bus.

  • you call getActivity().setTitle("Title"), but in this case you need to attach your Toolbar to the ActionBar by calling the setSupportActionBar() in your activity.

  • You can have a public instance of your Toolbar and access that instance from the fragment.

  • Finally, if you need the instance of your Toolbar(you may want to do something else with), you can simply get it this way:

    Toolbar bar=Toolbar.class.cast(getActivity().findViewById(R.id.toolbar));

Well, the last option would solve the problem only if the Toolbar hasn't been passed to the setSupportActionBar method.

If it has been, then you need to call this method in your activity:

supportActionBar.setDisplayShowTitleEnabled(false),

which will solve the problem.

However, I would suggest to use ButterKnife which will make it a little bit cleaner, here an example:

  Toolbar actionBar=findById(getActivity(),R.id.actionBar);
  actionBar.setTitle("Title");
Kerge answered 26/6, 2017 at 16:42 Comment(1)
You know what you are doing. Great answer, thank you.Vociferation
P
4

In Kotlin, I use

fun onAttach(...){
..
activity?.title = "My Title"
}
Phoney answered 17/10, 2019 at 6:50 Comment(0)
O
3

This work for me :

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.id_toolbar);

toolbar.setTitle("New Title");
Olga answered 11/10, 2017 at 2:56 Comment(0)
S
3

For me the problem was that for some reason the label was overwritten. I had to change it back to the string resource, in

 navigation.xml 

inside the fragment tag;

android:label="@string/android_trivia"
Spoke answered 24/1, 2019 at 9:15 Comment(0)
B
2

In your Activity declare the toolbar as public.

public class YourActivity : Activity
{
    public Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = .... // initilize your toolbar
    }
}

Then, from your fragment

((YourActivity) getActivity()).toolbar.Title = "Your Title";
Batholomew answered 20/9, 2016 at 10:46 Comment(0)
R
2
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                FragmentManager.BackStackEntry lastBackStackEntry=null;

                int lastBackStackEntryCount = getSupportFragmentManager().getBackStackEntryCount() - 1;
                if(lastBackStackEntryCount >= 0 )
                {
                    lastBackStackEntry = getSupportFragmentManager().getBackStackEntryAt(lastBackStackEntryCount);
                }
                Toast.makeText(MainActivity.this, ""+lastBackStackEntryCount, Toast.LENGTH_SHORT).show();
                if(lastBackStackEntryCount == -1)
                {
                    toolbar.setTitle("");
                    toolbar.setLogo(R.drawable.header_logo);
                }
                else
                {
                    toolbar.setTitle(lastBackStackEntry.getName());
                }
            }
        });
Redford answered 25/7, 2017 at 0:11 Comment(2)
this will also handle the first fragment problemRedford
this will help load the title from the backstack tag itself so just need provide the correct tag name also your title of the fragmentRedford
M
2

Here's one simple solution. In your activity that extends AppCompatActivity, you can do this:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

The inside its fragment, you can do this:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);
Mcniel answered 18/3, 2021 at 8:41 Comment(0)
M
1

You can change the title of your toolbar on the event OnAttach, something like this

        var toolbar = activity.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
        toolbar.Title = "New Title";
Meaganmeager answered 15/10, 2015 at 16:0 Comment(0)
E
1

If you are using a custom toolbar, this will help you:

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("Feedback");
Ezarra answered 14/3, 2017 at 12:47 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Cyprinid
B
1

You need to set the title in activity commiting the fragment and return the fragment

getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment, mainFragment).commit();
            toolbar.setTitle("ShivShambhu");
            return contentFragment;

This works for me.

Berkley answered 26/6, 2017 at 11:12 Comment(0)
T
0

xml

 <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_detail"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    app:contentInsetStart="0dp"
    app:contentInsetStartWithNavigation="0dp"
    android:background="@color/tool_bar_color">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:gravity="center">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#fff"
            android:textSize="16sp" />

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

Find TextView Id from toolbar

if you are using Activity

 TextView mTitle = findViewById(R.id.toolbar_title);
 mTitle.setText("set your title");

if you are using Fragment

 TextView mTitle = view.findViewById(R.id.toolbar_title);
 mTitle.setText("set your title");
Tackett answered 6/10, 2017 at 10:41 Comment(1)
Please don't post duplicate answers to multiple questions. Your answers should be tailored to each specific question, and questions that are the same should be flagged as duplicates.Deuteron

© 2022 - 2024 — McMap. All rights reserved.