简体   繁体   English

以编程方式在右上角的工具栏角中添加按钮

[英]Add button in top right toolbar corner programmatically

I'm trying to add a button in the top right corner of a toolbar, this is my code: 我正在尝试在工具栏的右上角添加一个按钮,这是我的代码:

   mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);

    verified_btn = new Button(getActivity());
    verified_btn.setBackgroundResource(R.drawable.ic_done_black_24dp);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);

    params.addRule(RelativeLayout.ALIGN_PARENT_END);
    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    params.width = 80;
    params.height = 80;

    verified_btn.setLayoutParams(params);
    verified_btn.setOnClickListener(this);
    mToolbar.addView(verified_btn);

but this is the result: 但这是结果:

在此输入图像描述

I have tried different way, but is always there, how I can do? 我尝试过不同的方式,但总是在那里,我该怎么做?

Add this to your activity. 将此添加到您的活动中。 This will add menu. 这将添加菜单。

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.right_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
        case R.id.action_home:
            //Do Whatever you want to do here.
            return true;
    }

    return super.onOptionsItemSelected(item);
}

Add new xml under res > menu > right_menu.xml res > menu > right_menu.xml下添加新的xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_home"
        android:orderInCategory="100"
        android:title="@string/title_activity_home"
        android:icon="@drawable/ic_home"
        app:showAsAction="ifRoom" />
</menu>

app:showAsAction="always" will always show your icon app:showAsAction =“always”将始终显示您的图标

NOTE : As you have fragment. 注意 :因为你有碎片。 you need to write this line in onCreate of fragment. 你需要在onCreate of fragment中写这一行。

setHasOptionsMenu(true);

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM