从Fragment更改ActionBar标题

时间:2015-10-14 10:35:57

标签: android android-fragments

我有4个片段

问题

当我在它们之间跳跃时,每个fragment都没有显示正确的标题。

我创建了一个gif来表明: http://i.imgur.com/QFTdH3w.gif

标题应与每个片段中的文本相同。

我的MainActivity看起来像这样:

public class MainActivity extends AppCompatActivity {  
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new InfoFragment(), "INFO");
        adapter.addFragment(new NavFragment(), "NAV");
        adapter.addFragment(new PetrolFragment(), "PETROL");
        adapter.addFragment(new CalcFragment(), "CALC");
        viewPager.setAdapter(adapter);
    }

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

我的每个片段都是这样的:

public class InfoFragment extends Fragment {

    public InfoFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((MainActivity) getActivity()).setActionBarTitle("INFO"); // here are other names according to each fragment
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_info, container, false);
    }
}

3 个答案:

答案 0 :(得分:4)

我不知道这是否是一种正确的方法,但您可以向viewpager添加页面更改侦听器,在onPageSelected方法中,您可以更改标题:

yourViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // change your title
                // inflate menu
                // customize your toolbar
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

答案 1 :(得分:1)

尝试以下代码

For Fragment title:

getActivity().getActionBar().setTitle("Fragment1");

答案 2 :(得分:1)

将此行添加到您的所有片段onCreateOnCreateView方法

((MainActivity) getActivity()).setActionBarTitle("Your title");

默认设置MainActivity

中的片段
viewPager.setCurrentItem(0);