android - Add button in top right toolbar corner programmatically -


i'm trying add button in top right corner of toolbar, 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 result:

enter image description here

i have tried different way, there, how can do?

add activity. 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 want 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" show icon

note : have fragment. need write line in oncreate of fragment.

sethasoptionsmenu(true); 

enter image description here


Comments

Popular posts from this blog

php - isset function not working properly -

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -