自定义菜单片段:
我可以更改片段更改菜单更改的方式吗?片段B等于上面的不同膨胀XML
菜单菜单工作ImageView
menuView
onClick
和片段更改更改菜单列表名称
public class BizForumFragment extends Fragment implements View.OnClickListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
ImageView menuView;
Context context;
RequestParse requestParse;
PagerAdapter adapter;
ViewPager viewPager;
public BizForumFragment() {
}
public static BizForumFragment newInstance(String param1, String param2) {
BizForumFragment fragment = new BizForumFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
context = this.getContext();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_biz_forum, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new PagerAdapter(getChildFragmentManager(), getContext());
viewPager.setAdapter(adapter);
menuView = (ImageView) view.findViewById(R.id.menuView);
menuView.setOnClickListener(this);
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(adapter.getTabView(i));
}
return view;
}
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(getContext(), menuView);
popup.getMenuInflater().inflate(R.menu.article_menu, popup.getMenu());
popup.show();
}
class PagerAdapter extends FragmentStatePagerAdapter {
String tabTitles[] = getResources().getStringArray(R.array.myLinks);
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public int getCount() {
return tabTitles.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ArticlesFragment();
case 1:
return new DiscussionFragment();
case 2:
return new NewsFragment();
}
return null;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_layout, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
答案 0 :(得分:0)
以前,我遇到过类似的问题。我在类中宣布了片段updateToolbar()
方法,并在ViewPager.OnPageChangeListener
中为所选片段调用它。
在方法updateToolbar()
中,我调用了以下代码:
getActivity().supportInvalidateOptionsMenu();
之后发生了菜单资源的重新膨胀。 您可以找到我的示例here