I added a refresh button to action-bar. When fragment loading that refresh button is creating in the action-bar. I have more than one fragment in my application, problem is when move between fragments and go back using back button using back button, action bar menu refresh button drawing several times. like this
following code I'm using
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_seebo_tv, container, false);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.seebo_tv, menu);
}
in main activity
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_refresh:
fragment=new ProgressFragment();
FragmentManager fragmentManagerProgress = getFragmentManager();
fragmentManagerProgress.beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
how can I fix this?
Try moving the call to setHasOptionsMenu(true); from onCreateView to onCreate instead.
Here's an example of a fragment adding a menu item: https://stackoverflow.com/a/31935887/798464
Related
I have an app that has 4 (0,1,2,3) Tabs and Fragments. My Actionbar has a menu item called "settings". When settings is clicked I want to navigate from the current Tab/Fragment to Fragment(3). In each of my java files associated with a fragment I am using the code below to handle menu clicks. I can launch an Intent successfully with this code but how can I navigate to another tab/fragment on menu item click? Thanks!
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
My actual code.
public class event extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.event, container, false);
setHasOptionsMenu(true);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.notify:
Log.i("4", "Notify pressed");
return true;
case R.id.action_settings:
Log.i("4", "Settings pressed");
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.custom_menu, menu);
}
}
If you're using a ViewPager then it's as simple as setCurrentItem(int currentItem)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
// ...
case R.id.settings:
((ViewPager)findViewById(R.id.of_view_pager)).setCurrentItem(3);
return true;
// ...
}
}
Edit in response to:
When I add that code some elements show up in red indicating I am doing something wrong. "findViewById" and "of_view_pager" are in red.
Sounds like you are in a Fragment and not an Activity in which case you probably want to find the ViewPager in your onCreateView method and store it in a field for later use in your onOptionsItemSelected method.
Something like this:
private ViewPager m_viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_changelog, container, false);
// Other stuff already in your `onCreateView`
m_viewPager = (ViewPager) view.findViewById(R.id.of_view_pager);
return view;
}
The of_view_pager is in red because that id doesn't exist. You need to replace it with the correct id of your ViewPager that you specified in the layout.
Ok, I know where I went wrong. I had a main activity and a fragment for each tab in my application. I had two action bar menus one included in the main activity and one custom menu for fragments. The code I was trying to run for switching tabs by clicking a menu button did not work if the onOptionsItemSelected code was in the fragment file. When I put the code in the main activity it worked fine.
I'm trying to add a button to my menu bar in my ListFragment class. When I click the button, nothing happens though. The onCreateOptionsMenu method is never being called in the class. I've tried everything to get it working but it still won't work. Has anyone got any solutions?
I've attached my code below:
public class FragmentZero extends ListFragment {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// use your custom layout
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_zero, container, false);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu items for use in the action bar
inflater.inflate(R.menu.main_fragment_zero, menu);
super.onCreateOptionsMenu(menu, inflater);
}
public boolean onOptionsItemsSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_refresh:
// check for updates action
RefreshButton();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Add setHasOptionsMenu(true) to your onCreateView() method and remove it in OnCreate().
So this was a pretty stupid error that I was having and I solved it thanks to everyone's help here.
I was spelling onOptionItemSelected wrong. I was adding an extra 's' after item.
As soon as I corrected this, the method started to work.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
RefreshButton();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void RefreshButton() {
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
I am trying to create an Action Bar with one option in a fragment but it doesn't work.
And I have followed all the steps which are indicated in the internet tutorials:
Create the function "onCreate", it doesn't appear by default, with the "sethasoptionmenu(true)".
Write the function "onCreateOptionsMenu" with the "inflater.inflate(R.menu.menu_fotos, menu);"
Create the function "onOptionsItemSelected"
With this, what I get is a normal options menu. But what I need is an Action Bar menu!
Can you help me?
I copy here the code of the fragment:
package com.carlesqf.laguerra;
import *.*;
public class FragmentContingutCapitols extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.activity_contingutcapitols, null);
// Getting the bundle object passed from "PantallaContingutCapitols"
Bundle b = getArguments();
String nomcap=LlistaCapitols.name[b.getInt("position")];
if (nomcap.contains("1700-1701 Les causes del conflicte:"))
v = inflater.inflate(R.layout.capitol1700, null);
else if ((nomcap.contains("1702 – Primers combats. Itàlia i front del Rin:")))
v = inflater.inflate(R.layout.capitol1702, null);
...
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_fotos, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Actually the actionbar menu is a normal options menu. Is NavigationDrawer what you're looking for?
The issue occurs when I attempt to switch from the Second Fragment to the First Fragment. I am using ActionBar Option Menu Icons to navigate back and forth between the different fragments.
Each fragment has its own menu that is associated with the individual option menu items. I cannot seem to figure out why I am able to transition from one the First Fragment to the Second Fragment, but am unable to do the reverse.
Does anything in my code stand out that would disable me from being able to navigate back to the previous fragment?
I was able to switch between the fragments without any issues in the past, but after I incorporated these option menu items to do the navigation, it stopped working.
Starting Fragment
public class SearchFragmentActivity extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_search_fragment,
container, false);
btnBasketball = (ImageButton) view.findViewById(R.id.btnBasketball);
btnBasketball.setOnClickListener(this);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
menu.clear();
inflater.inflate(R.menu.navigation_search_event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_more:
// do something with a dropdown
break;
}
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnBasketball:
changeFragment("Basketball");
break;
}
}
public void changeFragment(String sportName) {
Bundle bundle = new Bundle();
bundle.putString("SPORTNAME", sportName);
Fragment fragment = new SearchDetailsFragmentActivity();
fragment.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchFragment, fragment);
transaction.commit();
}
}
Second Fragment
public class SearchDetailsFragmentActivity extends Fragment {
TextView tvSportsName;
GridView gView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_search_details_fragment,
container, false);
String sportsName = getArguments().getString("SPORTNAME");
tvSportsName = (TextView) view.findViewById(R.id.tvSportsName);
tvSportsName.setText(sportsName);
// SportAdapter sAdapter = new SportAdapter(getActivity(), lstSports);
gView = (GridView) view.findViewById(R.id.gridViewSearch);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
menu.clear();
inflater.inflate(R.menu.navigation_search_details_event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_cancel:
changeFragment();
break;
}
return true;
}
public void changeFragment() {
Fragment fragment = new SearchFragmentActivity();
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.commit();
}
}
Options Menu associated with Second Fragment
<?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"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/action_cancel"
android:icon="#drawable/ic_content_remove"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="always"/>
</menu>
UPDATES
These changes allow me to navigate backwards from the SearchDetailsFragmentActivity >> SearchFragmentActivity using the SoftKey Back Button.
Changes to the changeFragment() method inside SearchDetailsFragmentActivity
public void changeFragment() {
Fragment fragment = new SearchFragmentActivity();
FragmentManager fm = getFragmentManager();
//FragmentTransaction transaction = fm.beginTransaction();
//transaction.setCustomAnimations(R.anim.cell_left_in,
//R.anim.cell_right_out);
//transaction.replace(R.id.searchDetailsFragment, fragment);
//transaction.commit();
fm.popBackStack();
}
inside the SearchFragmentActivity
public void changeFragment(String sportName) {
Bundle bundle = new Bundle();
bundle.putString("SPORTNAME", sportName);
Fragment fragment = new SearchDetailsFragmentActivity();
fragment.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchFragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
UPDATE 2
I placed a Log.e inside the OnOptionItemSelected() to see if the button was even firing properly and it appears as if it is not. There is nothing that is getting logged.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_cancel:
Log.e("IS THIS WORKING", "THIS IS WORKING"); <<< NOT FIRING
changeFragment();
break;
}
return true;
}
When replacing a fragment, you need to indicate whether or not that transaction is reversable (i.e. whether or not it goes onto the backstack). For the first fragment transaction, you usually won't want to do this (wouldn't want to pop to an empty view). For fragment replacements, you want to specify addToBackStack() with an optional tag (which can be later used with popBackStack(String)).
For example, in between these lines:
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.commit();
add:
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
I'm trying to have a Fragment inside a FragmentPagerAdapter have its own onclicklistener for a MenuItem.
In other words, I'm trying to use an Activity's onOptionsItemSelected method inside a Fragment
How do I do this?
I've tried using onContextItemSelected(MenuItem theItem) and onOptionsItemSelected(MenuItem theItem) to no avail
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
…
setHasOptionsMenu(true);
…
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.your_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.your_key_id:
saveRoute();
break;
default:
break;
}
return false;
}
Use this if you need one menu for all the pages.
Edit:
If you need a specific menu on a specific page, see this: Android: Showing Action Bar menu items depending on ViewPager