How can we set menu to toolbar - android

I have a activity and fragment ,i want to set a menu to mytoolbar in pre run time the icon has set but in run application it does not show anything.
in my activity:
public class MainActivity extends 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);
}
and in my fragment :
public class AuthenticationPasswordFragment extends BaseFragment implements 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);
}
in my menu is:
<item
android:id="#+id/item_authenticationpassword_confirm"
android:title="confirm"
android:icon="#drawable/everywhere_confirm"
app:showAsAction="always"
/>

Replace this setToolbar in activity :
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);
}
With this :
public void setToolBar(String title) {
mToolbar = findViewById(R.id.toolbar_everywhere_toolbar);
mTextViewToolbarTitle = findViewById(R.id.toolbar_title);
mTextViewToolbarTitle.setText(title);
}
And add this line to your onCreateView fragment or any fragment that you want add menu toolbar to it :
((MainActivity)getActivity()).setToolBar(getString(R.string.authenticationpassword_titletoolbar),R.menu.authenticationpassword_menutoolbar);

In the activity's onCreate method, set the toolbar with
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Then add this method.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.yourmenufile, menu);
return super.onCreateOptionsMenu(menu);
}
Then add menu click listener,
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
// do whatever
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you want to change the menu items and listeners while in different fragments, use interfaces to let the activity know which fragment is active and change accordingly.

If you want the method onCreateOptionsMenu inside a Fragment, add the codeline toolbar.setHasOptionsMenu(true) in onCreate of the activity where the Toolbar is set up.
The second option is to move the onCreateOptionsMenu into the Activity.
See this related StackOverflow question.
Report back if this works, I hope it helps you.

Related

Actionbar lost after rotation in dialog with toolbar

I'm implementing an app in Xamarin Android that contains a page that once you click on an actionbar button, you get a new dialog that contains a toolbar.
The simplified code is something like:
public class MyDialogFragment : MvxDialogFragment<MyDialogViewModel>
{
public MvxDialogFragment()
{
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
this.EnsureBindingContextIsSet(inflater);
var view = this.BindingInflate(Resource.Layout.dialog_view, null);
SetupToolbar(view);
return view;
}
private void SetupToolbar(View view)
{
Dialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
Android.Support.V7.Widget.Toolbar toolbar = view.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.dialog_toolbar);
((AppCompatActivity)Activity).SetSupportActionBar(toolbar);
Android.Support.V7.App.ActionBar actionBar = ((AppCompatActivity)Activity).SupportActionBar;
actionBar.Title = null;
HasOptionsMenu = true;
}
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
menu.Clear();
inflater.Inflate(Resource.Menu.menu_dialog, menu);
base.OnCreateOptionsMenu(menu, inflater);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
(...)
}
}
public override void OnPrepareOptionsMenu(IMenu menu)
{
(...)
base.OnPrepareOptionsMenu(menu);
}
The main workflow it works just fine, but there is a side effect when I rotate the screen while displaying the dialog.
If I do so, the actionbar buttons of the parent fragment(the one hosting the dialog), disappear till I recreate the view (ie: rotation).
Any ideas about how to solve this? I have tried several things like invalidate the parent menu after the dialog is closed, but it didn't work.
After some time investigating the problem, I don't think there is a way to make work 2 actionbars at the same time in a "native way".
My solution, in the end, was to manually handle the click events over the second actionbar.
public class MyDialogFragment : MvxDialogFragment<MyDialogViewModel>
{
public MvxDialogFragment()
{
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
this.EnsureBindingContextIsSet(inflater);
var view = this.BindingInflate(Resource.Layout.dialog_view, null);
SetupToolbar(view);
return view;
}
private void SetupToolbar(View view)
{
Dialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
toolbar = view.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.Title = null;
toolbar.InflateMenu(Resource.Menu.menu);
toolbar.MenuItemClick += HandlerMenuItemClick;
HasOptionsMenu = true;
}
public override bool HandlerMenuItemClick(object sender, Android.Support.V7.Widget.Toolbar.MenuItemClickEventArgs e)
{
switch (e.item.ItemId)
{
(...)
}
}
}
Hope it can helps anybody

How do I setSupportActionBar() in multiple fragments?

I have two support fragments sitting inside an AppCompatActivity. By design they each have unique Toolbar and Option Menus. The AppCompatActivity does not have a toolbar in it's layout as these are included in each fragment.
In each fragment, I setHasOptionsMenu(true); in onCreate().
In onCreateView() I am calling ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); where toolbar is the object bound to the xml Toolbar element.
In onCreateOptionsMenu(), I first make the call to super, then I call menu.clear() and finally inflate the menu with inflater.inflate(R.menu.searchbar_menu, menu);
Where this fails is in calling ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); in both fragments. In doing so, the options will only appear on the second fragment and not on the first. If I call it in only one fragment, the options appear as expected in only that one fragment. Of course, if I call it in neither, they do not appear at all.
Here is my code. Both Fragments are essentially identical with the exception of the menus inflated:
public class FeedFragment extends Fragment implements FeedView{
#BindView(R.id.toolbar)
Toolbar toolbar;
FeedPresenter presenter;
static final String TAG = "FEED_FRAGMENT";
/*
* Some boilerplate fragment setup code
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
ButterKnife.bind(this, view);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
setupToolar();
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.searchbar_menu, menu);
}
private void setupToolbar(){
toolbar.setPadding(0,ScreenUtil.getStatusBarHeight(this.getActivity()),0,0);
toolbar.setTitle("");
}
/*
* Other logic code unique to each fragment
*/
Does anyone know has I can set both fragments to have their toolbar options?
Thanks in advance.
When you call getActivity(), it returns the same instance of your Activity. The second fragment was initialized later than the first fragment, that why the Activity can only support action bar on the second fragment.
You could try this
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
AppCompatActivity baseActivity = (AppCompatActivity) getContext();
baseActivity.setSupportActionBar(yourToolbar);
}
}
What worked for me was setting suppoerActionBar according to which fragment is currently visible. You can use the following code:
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if(!hidden){
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
}
}

SearchView Menu Item Not Overriding Custom AppCompatToolbar

I'm working to implement a SearchView on my Fragment's RecyclerView as shown here. When the user taps the search button I want the Menu Item for the SearchView to Override the toolbar and display the area for them to search. If I don't use my custom style for the toolbar it works fine but when I do it get the images below.
Here is what I am currently getting:
This is the class that the EventListActivity inherits from:
public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstract Fragment createFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eventcalendar_activity_fragment);
// Manages our fragments. We can call it to add a fragment to an activity in code
FragmentManager fm = getSupportFragmentManager();
// Check if fragment of R.id already exits
// The FragmentManager saves out the list of fragments on rotation destruction or memory reclaim
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
// If the the fragment does not exist, create it
if(fragment == null) {
fragment = createFragment();
// Create a new fragment transaction, include one add operation in it, and then commit it
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
}
This creates the fragment that manages and works with the RecyclerView:
public class EventListActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
// Setting arguments for the new fragment created from the intent from EventFeedResultWrapper
EventListFragment fragment = new EventListFragment();
fragment.setArguments(getIntent().getExtras());
return fragment;
}
}
Fragment that holds the RecyclerViewthat the SearchView will interface with. This is where the search menu button is inflated. It is where I've been trying to modify the toolbar:
public class EventListFragment extends Fragment {
private RecyclerView mEventRecyclerView;
private EventAdapter mAdapter;
// Telling the FragmentManager that it is
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(R.layout.action_bar_center);
View sabView = ((AppCompatActivity)getActivity()).getSupportActionBar().getCustomView();
TextView titleTxtView = (TextView) sabView.findViewById(R.id.action_bar_title);
titleTxtView.setText("Events Calendar");
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.eventcalendar_fragment_event_list, container, false);
mEventRecyclerView = (RecyclerView) view.findViewById(R.id.event_recycler_view);
// RecyclerView requires a layout manager to work, layout manager is in charge of position items on screen
mEventRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
// Populate the menu instance
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.eventcalendar_menu, menu);
}
// When we edit a EventActivity this saves it back to the EventListActivity
// onResume over onStart because we cannot assume the activity will be stopped
// when another activity is in front of it. If the other activity is transparent
// then the activity might just get paused. If it is paused then onStart() will not be called
// but on resume will be called.
// NOTE: In general onResume() is the safest place to take action to update a fragment's view
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
// Read in the events saved in to EventFeedResultWrapper by the Async task in ParseEventFeedTask
EventFeedResultWrapper wrapper = (EventFeedResultWrapper) getArguments().getSerializable(ParseEventFeedTask.EXTRA_RESULTS_LIST);
// Make sure wrapper is not null, it will NEVER be null
if(wrapper == null){
throw new RuntimeException("Error: The wrapper is null!");
}
// Get all the events from the wrapper/serializable
List<Event> events = wrapper.getEventFeedResults();
// Gets the context that we don't use rofl
EventCal eventCal = EventCal.get(getActivity());
// Add all the events we got from the wrapper to our event manager eventCal
eventCal.addEvents(events);
// Check to see if the EventAdapter is already setup
if(mAdapter == null) {
mAdapter = new EventAdapter(events);
mEventRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
//Adapter here - removed code since it doesn't do anything with the toolbar
//RecycleView onClickLister - removed code since it doesn't do anything with the toolbar
}
This is the custom XML Style
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="24dp"/>
</LinearLayout>
Event Menu XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"/>
</menu>
Did you missed android:orientation="vertical". The text is displaying vertically. You want horizontal right?
Oh nvm i didn't understood it at first. The problem must be the inflating of the custom view, for some reason it seems it keeps the original view there and inflated it somewhere else. Give me 1s i'll update the answer when i find the issue
Check here: getSupportActionBar().setCustomView(view) does not fill entire actionbar
Similar problem. First and Second answer
EDIT2: Remove the code from EventListFragment onCreate. You don't need to inflate a searchView, you can use the default one.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
setOptionsMenu(menu);
}
public void setOptionsMenu(Menu menu) {
MenuItem search = menu.findItem(R.id.search);
SearchView searchView;
/**
* Setup the SearchView
*/
SearchManager searchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
final boolean[] modifiedOriginal = {false};
searchView = (SearchView) search.getActionView();
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(((Activity) context).getComponentName()));
MenuItemCompat.setOnActionExpandListener(search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
...
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
...
return true;
}
});
final EditText et = ButterKnife.findById(searchView, android.support.v7.appcompat.R.id.search_src_text);
et.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
String s = editable.toString();
if (!s.equals("") && !s.equals(" ")) {
...
}
}
});
ButterKnife.findById(searchView, android.support.v7.appcompat.R.id.search_close_btn).setOnClickListener(
view -> {
...
et.setText("");
}
);
}
}
You can leave your menu xml as it is.

how to get back to fragment from activity?

I have four fragments in an Activity C. they are behaving as tabs. I have to go from a fragment to a new Activity X. Now i want to come back to fragment from Activity X to fragment.
here is my main activity
'public class MainInterface extends ActionBarActivity {
ViewPager pager;
PagerTabStrip tab_strp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_interface);
MainPagerAdapter mapager = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(mapager);
tab_strp = (PagerTabStrip) findViewById(R.id.tab_strip);
//tab_strp.setTextColor(Color.WHITE);
//tab_strp.setTextSize(14,14);
//tab_strp.setTabIndicatorColor(Color.WHITE);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2196f3")));
getSupportActionBar().setTitle("Instructor");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
'
here is activity
'public class Discussions extends Fragment implements View.OnClickListener {
ImageButton post;
TextView dTitle;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.discussions,container,false);
post=(ImageButton)view.findViewById(R.id.ibDisc);
post.setOnClickListener(this);
dTitle=(TextView)view.findViewById(R.id.tvDiscTitle);
return view;
}
#Override
public void onClick(View view) {
Intent in=new Intent(getActivity(),PostDiscussion.class);
startActivity(in);
}
}'
Save the name of your fragment in sharedPreferences before navigating to new activity and onBackpressed of that new activity or when you want to come back to same fragment get the name from SharedPreferences and add that particular fragment to the earlier activity

toolbar menu item click in fragments

I know this question has been asked and but I am unable to solve my problem after looking at those answer. I have an Activity with a Fragment.
In fragment, I have added the toolbar and I want to handle toolbar menu item click events from the fragments.
In menu, I have added a single share button. I am getting the click event callback for the Up navigation (arrow home button) but I am not getting click event callback for the share button in my fragment.
Can some points me at what I am doing wrong here.
menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.rahul.haridasasampada.details.DescriptionActivity">
<item
android:id="#+id/action_share"
android:title="Share"
android:orderInCategory="100"
app:showAsAction="always"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>
</menu>
I have added toolbar to the fragment layout.
My Activity's code -
public class DescriptionActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_description);
if (savedInstanceState == null) {
Article articleExtra = (Article) getIntent().getParcelableExtra(DescriptionFragment.ARGS_EXTRA);
DescriptionFragment descriptionFragment = DescriptionFragment.newInstance(articleExtra);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, descriptionFragment)
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
getSupportActionBar().setTitle(R.string.app_name_in_kannada);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_description, menu);
Log.d("debug", "activity : onCreateOptionsMenu");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Log.d("debug","activity: action home has clicked");
onBackPressed();
return false;
case R.id.action_share:
Log.d("debug","activity: action share has clicked");
return false;
}
return super.onOptionsItemSelected(item);
}
}
My Fragments code -
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// some code
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBarActivity actionBarActivity = (ActionBarActivity) getActivity();
Toolbar toolbar = (Toolbar) getView().findViewById(R.id.toolbar_actionbar);
actionBarActivity.setSupportActionBar(toolbar);
toolbar.setOnMenuItemClickListener(this);
toolbar.inflateMenu(R.menu.menu_description);
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_share:
if (menuItem.getItemId() == R.id.action_share)
Log.d("debug","action share has clicked");
return true;
}
return false;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
Log.d("debug", "fragment : onCreateOptionsMenu");
MenuItem shareMenuItem = menu.findItem(R.id.action_share);
mShareActionProvider =(ShareActionProvider)MenuItemCompat.getActionProvider(shareMenuItem);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Log.d("debug","fragment : action home has clicked");
return true;
case R.id.action_share:
Log.d("debug","fragment: action share has clicked");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View detailFragmentView = inflater.inflate(R.layout.fragment_description, null);
return detailFragmentView;
}
From Android Docs, for Fragment:
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater)
Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu. For this method to be called, you must have first called setHasOptionsMenu(boolean).
so you want to control actionbar menu in Fragment, then you have to call setHasOptionsMenu method better in Fragment's onCreate(...):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
also important is that you should not use inflateMenu and onCreateOptionsMenu both together for same ToolBar, inflateMenu is for standalone without setting ToolBar as ActionBar.
Suggestion:
keep one ToolBar in Activity as ActionBar for your App, and another ToolBar standalone inside Fragment.
Hope this help!
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MyFragment extends Fragment implements Toolbar.OnMenuItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
Toolbar toolbar= (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(this);
return rootView;
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_menu:
//do sth here
return true;
}
return false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.training1_fragment, container,
false);
setHasOptionMenu(true);
return v;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save :
{
//Write here what to do you on click
return true;
}
}
return super.onOptionsItemSelected(item);
}
You should getPointer toolbar from your activity class and inflate menu in fragment class.
You can look this ex:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
activity = ((DescriptionActivity ) getActivity());
Toolbar tollbar=getView.findViewById(R.id.your_toolbar);
activity.setSupportActionBar(toolbar);
activity.toolbar.inflateMenu(R.menu.menu_search);
activity.toolbar.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_search:
break;
}
return false;
}
Please refer this for click of the Fragment optionMenu click link.

Categories

Resources