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