简体   繁体   English

将操作栏的标题从Fragmetn更改为Activity

[英]Change Title of Action Bar from Fragmetn to Activity

I have One MainActivity with Button A to navigate to Fragment A and initiall Title Set as "This is Main Title" 我有一个MainActivity,带有按钮A,可导航至片段A,并将初始标题设置为“ This is Main Title”

When I click Button A, Following Code gets Executed 当我单击按钮A时,将执行以下代码

   getSupportActionBar().setTitle("Profile");
            getSupportFragmentManager().beginTransaction().replace(R.id.container,new TrialProfile()).addToBackStack(null).commit();

and Now the Title Bar Text chnage to "Profile" But The Problem is When I press Back Button, The Title remains Same. 现在标题栏文本更改为“配置文件”,但问题是当我按“后退”按钮时,标题保持不变。 I want it to change to Original One ie "This is Main Title" 我希望将其更改为“原始标题”,即“这是主标题”

Can you please help me with this? 你能帮我吗?

在oncreate方法的当前活动中再次调用此方法

getSupportActionBar().setTitle("This is Main Title");
(getActivity()).setTitle("Profile");

To Change the title of Action Bar from Fragment to Activity 要将操作栏的标题从片段更改为活动

Create a method in activity like below: 在活动中创建一个方法,如下所示:

public void setTitleActionBar(String title) {
        getSupportActionBar().setTitle(title);
    }

Now you can call the method in fragment and activity for changing the title: 现在,您可以在片段和活动中调用方法以更改标题:

In Fragment: 在片段中:

  ((HomeActvitiy) getActivity()).setTitleActionBar("Fragment title");

In Activity call the method before fragment replace like below: 在Activity中,调用片段替换之前的方法,如下所示:

 setTitleActionBar("My Profile");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.home_container, new MyProfileFragment())
                .commit();

I hope its work for you. 希望它对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM