gpt4 book ai didi

android - 从 Fragment 更改 ActionBar 标题

转载 作者:太空狗 更新时间:2023-10-29 16:14:34 24 4
gpt4 key购买 nike

我有4个 fragment

问题

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

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

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

我的 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);
}

我的每个 fragment 都是这样的:

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);
}
}

最佳答案

我不知道这样做是否正确,但您可以向您的 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) {

}
});

关于android - 从 Fragment 更改 ActionBar 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33123076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com