4

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:

enter image description here

I have tried different way, but is always there, how I can do?

Piero
  • 9,173
  • 18
  • 90
  • 160

1 Answers1

2

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

<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

NOTE : As you have fragment. you need to write this line in onCreate of fragment.

setHasOptionsMenu(true);

enter image description here

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80