Navigating with sherlockactionbar in fragments doesnt work - android

my problem is when i click on a action bar item onOptionsItemSelected is called but not working.
I only want the back button to work.
Here is my code, this is in the SherlockFragment file:
actionbar = getSherlockActivity().getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
#Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.menu_detail, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.detailitem1:
break;
case android.R.id.home:
getActivity().onBackPressed();
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
The menu item is com.actionbarsherlock.view.MenuItem.
I added setHasOptionsMenu(true); in onCreate and tried onCreateView too.
The onBackPressed is this, its in the SherlockFragmentActivity:
#Override
public void onBackPressed() {
Saved = SP.getBoolean("saved", false);
if ((getSupportFragmentManager().findFragmentByTag("detail") == null)
| mTwoPane) {
ready = true;
} else
ready = false;
if (!Saved && ready) {
new AlertDialog.Builder(this)
.....
}else if (Saved && ready){
super.onBackPressed();
}else {
someListFragment Fragment = new someListFragment ();
Fragment .setArguments(getIntent().getExtras());
Fragment .setHasOptionsMenu(true);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, Fragment, "listview")
.commit();
}
}
In the onbackpressed the ready is true when we are in two pane mode, so when using tablet, or if we are in the first fragment(so the second is null).
If i press the back button everything works fine, the fragments are replaced.
But when i click on the back button in the action bar it just goes back to a previous activity.
Even if i chage the getActivity().onBackPressed(); onBackPressed's else statement i doesnt work.
Does anyone know whats the solution, what i did wrong?

Sorry i was a bit lazy, i forget that i had a onOptionsItemSelected in my FragmantActivity, and the back button is android.R.id.home everwhere, so i put an if statement there and voila.

Related

HashMap values from first fragment keeps called after the new fragment has been created

My problem is as follows:
I have one activity with many fragments. Main activity has "three dots" menu.
When I call a fragment, it has it's own menu (which is showing).
This fragment is a form with EditText fields, and checkboxes.
When a user changes something in those fields, and then press the "save" icon in the toolbar, the values get collected, and sent to the web service, and updated. BUT only the first time.
After going back (back arrow in toolbar), and returning to a fragment (new fragment gets created), after editing the fields, and pressing the "save" button, the form doesn't get saved/updated.
I debugged it, and found out that the "save" button which gets called for the second time, is actually the "save" button of the previous fragment.
The values in the editText fields gets collected inside a HashMap. And this HashMap gets updated and filled with new data inside new fragment. BUT when it gets to calling onOptionsItemSelected(), OLD DATA from the previous (or THE FIRST fragment) gets in the focus, and those data gets saved/updated.
So, my question is this: Is there a way to detach the menu items from the fragment, so when another (new) fragment is called, and gets created it attaches its own menu option to itself (not from the first fragment ever created)?
I tested it with System.identityHashCode(fragment), and when a user edit fields in "second" fragment, the hash code is OK, BUT when the "save" gets called hash code gets changed to the hash code of the first fragment.
This is the part of code from FormFragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_main, menu);
int itemId = 0;
for (ActionList menuItem : allData.getActionList()) {
menu.add(1, itemId, itemId, menuItem.getPrompt());
itemId++;
}
inflater.inflate(R.menu.menu_activity, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_favourite) {
if (valuesArray != null) {
((CommInterface) getActivity()).getUpdateList(valuesArray, taskUrl, dataItemId);
return true;
} else {
Toast.makeText(getActivity(), "Not updated!", Toast.LENGTH_SHORT).show();
return true;
}
}
for (ActionList menuName : allData.getActionList()) {
if (item.getTitle().equals(menuName.getPrompt())) {
((CommInterface) getActivity()).formMenuItemSelected(menuName.getActionName(), position);
return true;
}
}
return super.onOptionsItemSelected(item);
}
And the part of code from MainActivity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_choose_instance:
....
case android.R.id.home:
if (height > width) {
getSupportFragmentManager().popBackStack();
toolbarTitles.remove(toolbarTitlesCurrentNumber);
toolbarTitlesCurrentNumber--;
toolbar.setTitle(toolbarTitles.get(toolbarTitlesCurrentNumber));
if (toolbarTitlesCurrentNumber == 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}
} else if (...) {
....
}
default:
return super.onOptionsItemSelected(item);
}
}
Create the menu items under fragments not under activity,
see the previous discussion
Android Options Menu in Fragment
The answer to this problem is: use the getChildFragmentManager() in TabbedPagerAdapter.
I was using the Activity's getSupportFragmentManager() which is wrong when you are using NESTED fragments like in TabbedFragment which has a ViewPager, and a ViewPager has (child) Fragments inside.

AppCompact v21 back navigation with fragment menu

So.. I'm facing a problem that has been driving me crazy for the past hours.
I have an App using the AppCompact v21 and toolbar. I also handle back navigation using:
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
In combination with the parent activity on the manifest. Which works perfect....
My problem is:
I have an activity with 3 tabs with a viewpager and I need one of the fragments to have it's own menu.
I can inflate the menu just fine but once the menu is inflated the back arrow in that fragment don't work anymore. In the other 2 fragments of the view pager the back navigation through the toolbar still works.
Inside my fragment:
// Inside onCreate...
this.setHasOptionsMenu(true);
// Later on somewhere else...
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_submit, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// my menu logic goes here.
return true;
}
Any suggestions?
When you always return true in onOptionsItemSelected(), that means you've handled every menu item possible (including the Up button). You should instead return super.onOptionsItemSelected(item) in cases where you do not handle one of your items:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Your menu logic such as
case R.id.your_menu_item:
// Do something
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Menu appearing on other menu android

I am developing an app using actionbar sherlock. The problem I have is that I have the menus setup and all my xml files are correct since I get no compiler and logcat error.
THe problem I am having is that when I load a fragment A with its own specific menu everything is good. But when I then move to another fragment B, fragment A menu appears on fragment B. Any ideas as to whats causing this.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.product_allergy, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.productClear:
addtoList();
break;
}
return true;
}
The menu is belonged to Activty rather than fragments. Fragment A and B are in same activity, so when A adds some items into activity's menu and then it is replaced by Fragment B, the activity does not change, i.e., the menu is still there.
If you want your Fragment B to have different menu items, override the onCreateOptionsMenu() method, remember to setHasOptionsMenu(true) in Fragment's onCreate() method.
FYI, if you simply want to clear prior fragment's menu item, call menu.clear() in onCreateOptionsMenu().
EDIT:
When you are trying to handle the action bar callback in fragments, you should do something like below:
#override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.fragmentActionBarButton:
//your code
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Android: Use icon as back button without reloading previous activity

I have the following code to enable to home button to act as a back button. The problem I'm facing is from this activity if I use the real back button it simply goes back to the previous activity just as I left it. If I use the home button it's reloading the page so I lose what was previously done to it. I'm sure it's something simple I'm missing.
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.census_management_search, menu);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, CensusManagementActivity.class);
NavUtils.navigateUpTo(this, intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Instead of Intent and NavUtils try using onBackPressed() method.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The Home/Up button is supposed to reload the new activity. However, if you want to emulate the back button functionality, you can call finish() to return to the previous activity:
case android.R.id.home:
finish();
return true;

Fragment not receiving menu callbacks

I have a fragment class that extends Fragment and calls setHasOptionsMenu to participate in the menu. This class also implements onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
....
}
I'm dynamically loading this fragment using a FragmentTransaction in my Activity (that extends FragmentActivity).
However none of the menu callbacks (onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected) are being called (I've debugged with some breakpoints in those methods) and the menu isn't shown.
Am I missing something? Do I need to add something in my Activity?
I'm using the Android Compatibility Library, compiling with L11 SDK and testing in a Xoom.
EDIT: I've found the problem. My AndroidManifest is targeting L11, this seems to hide the menu button and prevent from the callbacks being called. However if I remove this from the manifest I loose some other features I need (for example the activated state in lists). Does anyone know how to solve this issue (enable the menu button) without removing the targetSdkVersion=11 from the Manifest?
Aromero,
Don't forget to override the onCreateOptionsMenu using the fragment version of the method, similar to this:
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.queue_options, menu);
super.onCreateOptionsMenu(menu, inflater);
}
This goes in the fragment, by the way, and adds to the inflated menu of the Activity, if there is one. Had the same problem myself, until I figured this out.
Kim
If you're having this problem with ActionBarSherlock, you need to make sure your Fragments are SherlockFragments, not mere SupportFragments, and that what you're overriding is
public void onPrepareOptionsMenu (com.actionbarsherlock.view.Menu menu) {
NOT
public void onPrepareOptionsMenu (android.view.Menu menu) {
If you do the latter, you should get some sort of warning about the function being final and you being unable to override it. This is a warning that you're trying to override the wrong function!
If you fix the error by switching the class from SherlockFragment to a mere Fragment, you can create the function . . . but it won't get called.
I had the same problem, but i think its better to summarize and introduce the last step to get it working:
Add setHasOptionsMenu(true) method in your Fragment's onCreate(Bundle savedInstanceState) method.
Override onCreateOptionsMenu(Menu menu, MenuInflater inflater) (if you want to do something different in your Fragment's menu) and onOptionsItemSelected(MenuItem item) methods in your Fragment.
Inside your onOptionsItemSelected(MenuItem item) Activity's method, make sure you return false when the menu item action would be implemented in onOptionsItemSelected(MenuItem item) Fragment's method.
An example:
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_menu_item:
// Do Activity menu item stuff here
return true;
case R.id.fragment_menu_item:
// Not implemented here
return false;
default:
break;
}
return false;
}
Fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
....
}
#Override
public void onCreateOptionsMenu(Menu menu) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_menu_item:
// Not implemented here
return false;
case R.id.fragment_menu_item:
// Do Fragment menu item stuff here
return true;
default:
break;
}
return false;
}
I hope this will be helpful.
Cheers.
If you have an activity and a fragment that each loads menu items then you need to take special care of which overrides you use.
Activities can override onOptionsItemSelected and onMenuItemSelected, however fragments can only override onOptionsItemSelected.
If you override onMenuItemSelected in your activity and onOptionsItemSelected in your fragment, your fragment override will never get triggered.
Instead, use onOptionsItemSelected in both activity and fragment.
You need to make sure you call setHasOptionsMenu(true); onCreate or onCreateView is called in your fragment.
You also need to implement the override of onCreateOptionsMenu inside your fragment.
Another possible case is when you use a common id for a common action in each fragment; for instance R.id.action_add
Today I had such situation: hitting the option menu [add] was invoked the "wrong" onOptionItemSelected because each fragment (replaced dynamically using a DrawerLayout) had the same R.id.action_add.
Short story, if you have such situation always check that your fragment is visible:
if (!isVisible()) return false;
Long story, pay attention at the onOptionItemSelected chain!
MainActivity
|
| onOptionItemSelected
+-----------------------
| return false
|
MyCoolFragment1
|
| onOptionItemSelected
+-----------------------
| return false
|
MyCoolFragment2
|
| onOptionItemSelected
+-----------------------
| return true
|
[item selection handled]
If you add your fragments with (something like) this:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, MyCoolFragment1.newInstance())
.commit()
and you have defined the same id for a common action (let's say R.id.action_add) in each fragment;
don't forget to add this line to each: if (!isVisible()) return false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!isVisible()) return false; // <-- Not visible? skip!
if (item.getItemId() == R.id.action_add) {
//.TODO whatever
return true; //.Handled!
}
return false; //.Skip
}
I had this problem when I was using the ViewPagerIndicator in conjunction with ActionBarSherlock. Although it appeared this was fixed I still ran into the problem. The work around I found was to call into the fragment manually.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "From activity", Toast.LENGTH_SHORT).show(); // TODO
Fragment currentFragment = mAdapter.getItem(mPager.getCurrentItem());
if (currentFragment != null && currentFragment instanceof SherlockFragment)
{
((SherlockFragment)currentFragment).onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
I've found the problem. The AndroidManifest is targeting SDK 11, this seems to hide the menu button and prevent from the callbacks being called. I assume that this breaks the compatibility of the menu button that seems to be replaced by the action bar in Android 3.0
I think you have implemented onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected in the class that extends Fragment. Try by doing that in your Activity class where you are loading this fragment
From the android developer site - link
Note: If you inflate menu items from a fragment, via the Fragment
class's onCreateOptionsMenu() callback, the system calls
onOptionsItemSelected() for that fragment when the user selects one of
those items. However, the activity gets a chance to handle the event
first, so the system first calls onOptionsItemSelected() on the
activity, before calling the same callback for the fragment. To ensure
that any fragments in the activity also have a chance to handle the
callback, always pass the call to the superclass as the default
behavior instead of returning false when you do not handle the item.
Therefore Marco HC is the best answer of all.
If your toolbar is defined in the parent activity xml, make sure you do this in your fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
....
Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
}
And then of course, override onCreateOptionsMenu like below
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.edit_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
This is the only solution that worked for me!
I had same problem and solution that worked for me is:
Remove or comment any onOptionsItemSelected() ,onMenuItemSelected() even onPrepareOptionMenu() and leave in Activity onCreateOptionsMenu() only:
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
In Fragment class, in onCreateView(), put:
setHasOptionsMenu(true);
In Fragment class add :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_insert:
//doing stuff
return true;
}
return false;
}
Tested and worked on Android 4.4

Categories

Resources