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
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.
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. :)
If you have setSupportActionBar in Your Activity then you can easily change the toolbar title from your fragment
((YourActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
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 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.