android - 我们如何将菜单设置为工具栏
问题描述
我有一个活动和片段,我想在运行前设置一个菜单到 mytoolbar 图标已设置但在运行应用程序中它不显示任何内容。
在我的活动中:
公共类 MainActivity 扩展 AppCompatActivity {
private TabLayout mTabLayout;
private TextView mTextViewTabOne;
private TextView mTextViewTabTwo;
private TextView mTextViewTabThree;
private android.support.v7.widget.Toolbar mToolbar;
private TextView mTextViewToolbarTitle;
private AlertDialog mAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setLocale("fa");
getSupportFragmentManager().beginTransaction().replace(R.id.framelayout_mainactivity_fragmentcontainer, new AuthenticationPasswordFragment()).commit();
setToolBar(getString(R.string.addbank_toolbartitle));
}
public void setToolBar(String title) {
mToolbar = findViewById(R.id.toolbar_everywhere_toolbar);
mTextViewToolbarTitle = findViewById(R.id.toolbar_title);
mTextViewToolbarTitle.setText(title);
}
在我的片段中:
公共类 AuthenticationPasswordFragment 扩展 BaseFragment 实现 BaseAuthenticationContract.View {
private TextInputEditText mEditTextPassword;
private TextInputLayout mTextInputEditTextPassword;
private View mRoot;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRoot=inflater.inflate(R.layout.fragment_authenticationpassword,null);
return mRoot;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.authenticationpassword_menutoolbar,menu);
}
在我的菜单中是:
<item
android:id="@+id/item_authenticationpassword_confirm"
android:title="confirm"
android:icon="@drawable/everywhere_confirm"
app:showAsAction="always"
/>
解决方案
在活动中替换此 setToolbar :
public void setToolBar(String title,int resourceMenu) {
mToolbar = findViewById(R.id.toolbar_everywhere_toolbar);
mTextViewToolbarTitle = findViewById(R.id.toolbar_title);
mTextViewToolbarTitle.setText(title);
mToolbar.inflateMenu(resourceMenu);
}
有了这个 :
public void setToolBar(String title) {
mToolbar = findViewById(R.id.toolbar_everywhere_toolbar);
mTextViewToolbarTitle = findViewById(R.id.toolbar_title);
mTextViewToolbarTitle.setText(title);
}
并将这一行添加到您的 onCreateView 片段或您想要向其添加菜单工具栏的任何片段:
((MainActivity)getActivity()).setToolBar(getString(R.string.authenticationpassword_titletoolbar),R.menu.authenticationpassword_menutoolbar);
推荐阅读
- wordpress - Woocommerce 产品无法从购物车中删除
- php - 在 TYPO3 后端添加 jQuery 函数
- c# - 如何自定义 .Net Json 序列化设置来处理 json 关键字段?
- grep - 如何使用 .txt 词汇 grep 多行,仅匹配第一个单词作为变量?
- devextreme - devextreme-react datagrid,分别启用编辑器以插入(新行)和编辑(现有行)
- python - 用蛇中的图像替换立方体
- reactjs - 如何使用 jest 和酶访问道具内的 div,如头像,卡片头的动作(来自 materialUI 的卡片元素的子元素)div
- android - 满足约束时如何避免多个工人同时运行?
- codeigniter - 如何在codeigniter中提交表单后重定向url
- node.js - 在angularjs中通过history.replacestate更改url时如何停止页面刷新?