Set Title inToolBar from Fragment in Android

孤者浪人 提交于 2019-12-02 22:28:56

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.

I do this like this: from the fragment call

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

Also you can call any function of your parent Activity like this:

YourActivity mYourActiviy = (YourActivity) getActivity();
mYourActivity.yourActivityFunction(yourParameters);

In Kotlin.

In fragment:

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

In activity:

setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
Rahul Nagane

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

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

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

((YourActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
Pankaj Negi

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

Mesah Barus

This work for me :

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

toolbar.setTitle("New Title");

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";
Sai Gopi N

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

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("Feedback");

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");
Nizam Alam
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());
                }
            }
        });

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";

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.

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");

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"

In Kotlin, I use

fun onAttach(...){
..
activity?.title = "My Title"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!