onCreateOptionsMenu() does not work in Fragment - java

I am trying to implement a search Filter in my Fragment, but it does not let me. I used the same code in Activity before and it worked. Whenever I type something, the onCreateOptionsMenu() does not get called. The App looks like this : [![app Picture][1]][1]
As you can see I type something in the top and it won't get filtered.
My Fragment code: `
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setMenuVisibility(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.fragment_tab1, container, false);
if(getArguments() != null){
String yourText = getArguments().getString("interessen");
System.out.println(yourText);
}`
.
.
.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menuevents, menu);
super.onCreateOptionsMenu(menu, inflater);
MenuItem searchitem = menu.findItem(R.id.searchEvent);
//searchitem.setVisible(false);
final SearchView searchView = (SearchView) searchitem.getActionView();
final List<Event> allEvents = new ArrayList<>();
allEvents.addAll(eventList);
searchitem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
eventList.clear();
eventList.addAll(allEvents);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
eventList.clear();
eventList.addAll(allEvents);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
eventListAdapter.getFilter().filter(newText);
return false;
}
});
I did not copy the EventListAdapter in, becuase this should work just fine. Its just that the Fragment does not get Access to the SearchItem.
Anybody? :)
[1]: https://i.stack.imgur.com/JkLcL.png

You've called setMenuVisibility(), which means your Fragment is specifically opting out of having its menu being shown. It is expected that when your menu isn't shown, onCreateOptionsMenu() is not triggered.
Remove that line of code to have your menu actually be visible.

Related

Android Studio: How to implement backbutton in ActionBar from Fragments

I'm having trouble implementing a backbutton in the ActionBar in a Fragment. Since this is a Fragment I don't have access to getSupportActionBar(); and each time I use this, or similar code:
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
only results in NullPointerExceptions.
I've looked at numerous similar questions on StackOverflow but most of them are specified to Activities or AppCompatActivities, which do not work in Fragments. Using
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
only results in NullPointerExceptions. The other similar questions and answers have not helped me with this problem so I had to create a new topic.
This is where I get the error:
public class ExampleFragment extends Fragment{
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true); //This results in NullPointerException
inflater.inflate(R.menu.example_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
getActivity().getSupportFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
}
You need to receive supportActionBar.
public class ExampleFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
ActionBar actionBar = ((AppCompatActivity)requireActivity()).getSupportActionBar();
if (actionBar!=null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
requireActivity().getSupportFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I did not get this to work so I changed the structure of the View and made it to an Activity which has more support in dealing with this issue.
#Override
protected void onCreate(#Nullable Bundle savedInstance){
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}

android: menu won't show up

I'm trying to have a different menu show up when a fullscreen dialog is shown but it won't appear. Instead, a blank menu appears.
I've tried calling it conditionally from the original activity and I've tried calling it from the dialog view.
Here's the fullscreen Dialog View:
public class MyMainView extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.layout.layout_full_screen_dialog);
setHasOptionsMenu(true);
}
#Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
new MenuInflater(this.getActivity()).inflate(R.menu.add_to_user_library, menu);
//inflater.inflate(R.menu.add_to_user_library, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.add_to_user_library, container, false);
// view code here
return view;
}
}
Menu XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".result.ResultActivity">
<item
android:id="#+id/save"
android:icon="#drawable/ic_check"
android:showAsAction="ifRoom"
android:title="#string/menu_save_library"
tools:ignore="AppCompatResource" />
<item
android:id="#+id/go_back"
android:icon="#drawable/ic_clear"
android:showAsAction="ifRoom"
android:title="#string/menu_save_library"
tools:ignore="AppCompatResource" />
</menu>
From the activity
public final class ResultActivity extends CoreActivity {
public static void startActivityForResult(Activity a, Result r, int requestCode) {
Intent i = new Intent(a, ResultActivity.class);
i.putExtra(EXTRA_RESULT, r);
a.startActivityForResult(i, requestCode);
a.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_result, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.case1:
{
Bundle b = new Bundle();
String myString = (String.valueOf(_result.myString));
b.putString("myString", myString);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
String timeStamp = sdf.format(new Date(_result._timestamp));
b.putString("timeStamp", timeStamp);
String myString1 = _result.myString1;
b.putString("myString1", myString1);
//show the dialog
DialogFragment newFragment = new MyMainView();
newFragment.setArguments(b);
newFragment.show(getFragmentManager(),"SaveIt");
return true;
}
case case2:
{
//etc...
Right now, when the dialog shows up but the menu appears right before it loads then becomes blank.
What I see is the following.

SearchView in fragment (inflated menu in activity)

I get NPE on SearchView.OnQueryTextListener.
/res/menu/order_toolbar.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/order_menu_search"
android:icon="#drawable/ic_search"
android:title="#string/order_menu_search"
app:actionViewClass="android.support.widget.v7.SearchView"
app:showAsAction="ifRoom|withText" />
<item
android:id="#+id/order_menu_checkmark"
android:icon="#drawable/ic_checkmark"
android:title="#string/order_toolbar"
app:showAsAction="ifRoom|withText" />
ActivityOrder.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.order_toolbar, menu);
mMenuCheckmark = menu.findItem(R.id.order_menu_checkmark);
mMenuCheckmark.setVisible(false);
return super.onCreateOptionsMenu(menu);
}
FragmentOrder.java
#Override
public void onPrepareOptionsMenu(Menu menu){
MenuItem menuItem = menu.findItem(R.id.order_menu_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(getActivity(), "" +newText, Toast.LENGTH_SHORT).show();
return false;
}
});
}
I'm inflating menu in Activity (i need to hide checkmark and enable it later after the user made some input, all the logic is in the activity), and in Fragment, I have RecyclerView and I need to implement search (in the toolbar). So basically, I need to access that SearchView INSIDE FRAGMENT only.
I have been trying to find anything but nothing helps, if I inflate menu in fragment then I get doubled icons in the toolbar.
setHasOptionsMenu(true);
is already added in onCreate
Also i tried this:
1. inflate the menu in fragment (removed onCreateOptionsMenu in activity)
2. passed menuItem (checkmark) back to activity trough interface so i can access checkmark
3. still getting NPE if i set listener on searchview
I make option menu in fragment. Like this,
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
...
setHasOptionsMenu(true);
...
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_menu, menu);
menu.findItem(R.id.menu_1).setIcon(ContextCompat.getDrawable(activity, R.drawable.ic_bar_search));
searchView = (SearchView) menu.findItem(R.id.menu_1).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
return false;
}
});
....
}
Not sure, you call "searchView.setOnQueryTextListener" from onCreateOptionsMenu.
Solved:
mMenuSearch = (SearchView) menu.findItem(R.id.order_menu_search).getActionView();
mMenuSearch.setOnQueryTextListener(this);
added implements SearchView.OnQueryTextListener on Fragment and 2 new Override methods onQueryTextSubmit and onQueryTextChanged

Where to write java code in Android app

I just started learning how to create Android app and I'm stuck with methods in MainActivity.java. I don't know where to write my java code because the app is crashing.
package com.cidecode.loveometer;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Things you want to be created when the activity is started should be in the onCreate method (buttons and onClickListeners etc). If for example you have a button you have stated an onClick name for in the xml file (rather than put an onClickListener on it) then you can put that function where you like as long as it is not after the last curly brace that finishes the activity. You should try the new boston tutorials on youtube, I found they explained a lot and helped me understand where I actually needed to put things.

onCreateOptionsMenu not getting called inside the Fragment class

public class FragmentClass extends android.support.v4.app.Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Log.d("Does", "get called");
inflater.inflate(R.menu.menuItem, menu);
}
}
onCreateOptionsMenu method is never called even though i have placed setHasOptionsMenu(true) inside my onCreate Method.
This is how my Activity class looks like.
https://github.com/jfeinstein10/SlidingMenu/blob/master/example/src/com/slidingmenu/example/fragments/FragmentChangeActivity.java
More update: This is my method inside Fragment Class.
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
inflater.inflate(R.menu.facesheet, menu);
super.onCreateOptionsMenu(menu,inflater);
}
This is inside the BaseActivity class.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
I think you are not overriding the right method.
Try this code :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menuItem, menu);
return true;
}
Source link.
Additional try to call setMenuVisibility(true);

Categories