Set a title in Toolbar from fragment in Android

后端 未结 17 809
逝去的感伤
逝去的感伤 2021-01-31 03:40

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

17条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 04:24

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

提交回复
热议问题