Search code examples
androidandroid-fragmentsandroid-actionbar

change custom ActionBar title from fragment in android


Hi in the below code I have a one fab button if I press the fab button replacing one fragment with another fragment in the meanwhile I am changing the title also.

But fragments are replaced but the title is not changing.

Can anyone help me

OneFragement.java:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the borderdashboard for this fragment

        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Task List");
        View rootView = inflater.inflate(R.layout.account_list, container, false);
        setHasOptionsMenu(true);
        setSearchtollbar();

        FloatingActionButton fb = rootView.findViewById(R.id.fab);
        fb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isDuplicate = "false";
                Bundle args = new Bundle();
                args.putString("isDuplicate", String.valueOf(isDuplicate));

                fragment = new TaskCreateFragement();
                sessionId = getActivity().getIntent().getStringExtra("sessionId");
                fragment.setArguments(args);
                ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Create New Task");
                loadFragment(fragment);
            }
        });

SecondFragment.java:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the borderdashboard for this fragment

        ((AppCompatActivity) getContext()).getSupportActionBar().setTitle("Create New Task");

MainActivity.java:

  toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
      //  getSupportActionBar().setTitle("DASHBOARD");

        final ActionBar ab = getSupportActionBar();
        ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        ab.setCustomView(R.layout.toolbar_spinner);
        if (ab != null) {
            ab.setDisplayShowTitleEnabled(false);
            mTitle = (TextView) findViewById(R.id.toolbar_title);
            mTitle.setText("DASHBOARD");
            mTitle.setGravity(Gravity.CENTER_HORIZONTAL);
//            Typeface typeface = Typeface.createFromAsset(getApplicationContext ().getAssets (), "fonts/astype - Secca Light.otf");
            //          mTitle.setTypeface (typeface);
        }
        ab.setHomeAsUpIndicator(R.drawable.menu);
        ab.setDisplayHomeAsUpEnabled(true);

Solution

  • Create method in your Activity

    public void setActionBarTitle(String title) {
        mTitle.setText(title);    // as you used custom view
    }
    

    In SecondFragment change title in onCreate or onResume

    ((YourActivity)getActivity()).setActionBarTitle("Create New Task");