我有一个框架,我在其中放置了不同的 fragment 。有些显示了操作栏,有些则没有。但下面给出的操作栏并不像其他操作栏那样显示。
public class AFragment extends Fragment {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_a, container, false);
ButterKnife.bind(this, view);
setHasOptionsMenu(true);
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_a, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_a) {
//getFragmentManager().popBackStackImmediate();
}
return super.onOptionsItemSelected(item);
}
}
这个 fragment 是从之前的 fragment 中调用的
AFragment aFragment = new AFragment ();
getFragmentManager().beginTransaction()
.replace(R.id.fragment, aFragment , "fragment_a")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
顺便说一句,我没有在上一个 fragment 中显示操作栏。
如果需要,styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppActionBar" parent="AppTheme">
<item name="android:windowActionBarOverlay">true</item>
<item name="windowActionBarOverlay">true</item>
</style>
最佳答案
对于 fragment ,您必须确保在 onCreate()
方法以及现在的 onCreateView()
方法中设置 setHasOptionsMenu()
。
然后确保将工具栏(如果添加到 fragment 布局中)设置为 Activity 的工具栏。
public class AFragment extends Fragment {
View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_a, container, false);
ButterKnife.bind(this, view);
//moved to onCreate() method
//setHasOptionsMenu(true);
//set toolbar as the default for the activity class if AppCompat
((AppCompatActivity) getActivity()).setSupportActionBar(/*your toolbar goes here*/);
//set toolbar is activity class is not AppCompat
getActivity().setActionBar(/*your toolbar goes here*/);
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_a, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_a) {
//getFragmentManager().popBackStackImmediate();
}
return super.onOptionsItemSelected(item);
}
}
关于java - 选项菜单未在 fragment 中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171588/