34

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..

CoolMind
  • 26,736
  • 15
  • 188
  • 224
AndroidMech
  • 1,676
  • 3
  • 20
  • 31
  • 7
    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. – AndroidMech Nov 24 '14 at 10:34

18 Answers18

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);
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Hemant Singh
  • 924
  • 1
  • 6
  • 13
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)
CoolMind
  • 26,736
  • 15
  • 188
  • 224
14

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

((YourActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
ANUJ GUPTA
  • 905
  • 13
  • 22
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.

Steffen
  • 2,197
  • 2
  • 24
  • 38
10

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

getActivity().setTitle("your name");
Derlin
  • 9,572
  • 2
  • 32
  • 53
Rahul Nagane
  • 131
  • 1
  • 7
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. :)

Mitch
  • 1,556
  • 1
  • 17
  • 17
Pankaj Negi
  • 1,558
  • 1
  • 16
  • 23
  • 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 methods – Mitch Aug 29 '19 at 17:00
  • it shouldnt be hardly or complex like that – withoutOne Jan 26 '22 at 16:30
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)
    }
kevincodes_
  • 219
  • 4
  • 4
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");
Community
  • 1
  • 1
nullbyte
  • 1,178
  • 8
  • 16
4

In Kotlin, I use

fun onAttach(...){
..
activity?.title = "My Title"
}
Aziz
  • 1,976
  • 20
  • 23
3

This work for me :

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

toolbar.setTitle("New Title");
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
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";
Drunken Daddy
  • 7,326
  • 14
  • 70
  • 104
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());
                }
            }
        });
Kukic Vladimir
  • 1,010
  • 4
  • 15
  • 22
Nizam Alam
  • 21
  • 2
2

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"
7RedBits.com
  • 454
  • 6
  • 6
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";
lagvjjt
  • 19
  • 2
1

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

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("Feedback");
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
saigopi.me
  • 14,011
  • 2
  • 83
  • 54
  • 3
    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. – Dev-iL Mar 14 '17 at 17:07
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.

Prashant.J
  • 739
  • 7
  • 12
1

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);
prateek
  • 440
  • 4
  • 12
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");
  • 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. – user229044 Oct 06 '17 at 12:36