首页 > 解决方案 > 我们如何将菜单设置为工具栏

问题描述

在此处输入图像描述我有一个活动和片段,我想在运行前设置一个菜单到 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"
    />

标签: androidlayoutmenu

解决方案


在活动中替换此 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);

推荐阅读