如何更新从片段工具栏选项 [英] How to update toolbar options from Fragment
问题描述
我有一个活动一个tablayout,navigationdrawer和工具栏。
新增3碎片viewpager并添加viewpager到tablayout:
我的活动code片断:
I am having a tablayout, navigationdrawer and toolbar in an activity. Added 3 fragments to viewpager and added viewpager to tablayout: Code snippet of my activity:
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
现在在每个片段中我要显示的工具栏不同的选项:
于是,我试图访问工具栏在我的片段是这样的:
Now in each fragment I have to display different options in toolbar: So I tried to access the toolbar in my fragment like this:
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
_context = getActivity();
mainView = inflater.inflate(R.layout.frag1, container, false);
mToolbar =(Toolbar) mainView.findViewById(R.id.app_bar);
mToolbar.setTitle("");
toolbarTitle = (TextView) getActivity().findViewById(R.id.toolbar_title);
toolbarTitle.setText("Fragment1");
toolbarTitle.setSelected(true);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(mToolbar);
}
充气需要的菜单中onCreateOptionsMenu(菜单菜单,MenuInflater气筒)
但需要在工具栏菜单中不膨胀。我们怎样才能改变片段的工具栏选项。
Inflated the required menu in onCreateOptionsMenu(Menu menu, MenuInflater inflater) but not inflating as required the menu in toolbar. How can we change the toolbar options in Fragment.
推荐答案
这是为我工作。这是我在的onCreate。 (刷新的是我自己的接口)。
This is working for me. This is all I have in onCreate. (Refreshable is an interface of my own).
public class SummaryFragment extends Fragment implements Refreshable {
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
而这正是我吹菜单。
And this is where I inflate the menu.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.save, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
{
File csvFile = saveResults();
etc...
现在它走了,但我即使在我MainActivity有不同的菜单和两个都是present当我的摘要标签是活跃的。
It's gone now, but I even had a different menu in my MainActivity and the two were both present when my Summary tab was active.
这篇关于如何更新从片段工具栏选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!