我尝试使用 setHasOptionsMenu(true); 时,我的工具栏按钮未显示在 fragment 中。当我单击抽屉导航项目时,它会为每个 fragment 加载新 fragment ,我想显示不同的操作栏按钮(通知或保存)。以下是我的代码,提前致谢。
以下是我的 fragment 代码:(抽屉导航中的所有 fragment 都相同)
public class Company1 extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_company_profile,container, false);
init(view);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAddDialog();
}
});
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.company_profile, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.notification:
break;
}
return super.onOptionsItemSelected(item);
}
}
这是company_profile.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="@+id/notification"
android:icon="@drawable/ic_action_notification"
android:title="@string/mnuNotificationText"
app:showAsAction="always"/>
</menu>
最佳答案
请检查此代码 fragment
public class Company1 extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_company_profile,container, false);
setHasOptionsMenu(true);
init(view);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAddDialog();
}
});
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.company_profile, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.notification:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
//You can change menuitem property
//menu.findItem(R.id.notification).setVisible(true);
super.onPrepareOptionsMenu(menu);
}
}
关于android - 操作栏按钮未显示在 fragment 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38695933/