I am having some trouble getting an options menu working for each fragments of my activity using ActionBarSherlock API.
I have placed setHasOptionsMenu(true) inside my onCreateView, but onCreateOptionsMenu inside fragments is never called.
My Main Activity
public class EvolutionActivity extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
addTab(getResources().getString(R.string.fragment_measurement_title), TabFragmentMeasurement.class, null);
addTab(getResources().getString(R.string.fragment_workout_title) , TabFragmentWorkout.class, null);
addTab(getResources().getString(R.string.fragment_exercise_title), TabFragmentExercise.class, null);
}
}
Tab activity abstract class TabActivity.class
public abstract class TabActivity extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
/*
* Create the ViewPager and our custom adapter
*/
mViewPager = new ViewPager(this);
adapter = new TabsAdapter( this, mViewPager );
mViewPager.setAdapter( adapter );
mViewPager.setOnPageChangeListener( adapter );
/*
* We need to provide an ID for the ViewPager, otherwise we will get an exception like:
*
* java.lang.IllegalArgumentException: No view found for id 0xffffffff for fragment TabFragmentMeasurement{40de5b90 #0 id=0xffffffff android:switcher:-1:0}
* at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:864)
*
* The ID 0x7F04FFF0 is large enough to probably never be used for anything else
*/
mViewPager.setId( 0x7F04FFF0 );
super.onCreate(savedInstanceState);
/*
* Set the ViewPager as the content view
*/
setContentView(mViewPager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings:{
Intent intent = new Intent(this, ParametersActivity.class);
startActivity(intent);
break;
}
}
return super.onOptionsItemSelected(item);
}
/**
* Add a tab with a backing Fragment to the action bar
* #param titleRes A string resource pointing to the title for the tab
* #param fragmentClass The class of the Fragment to instantiate for this tab
* #param args An optional Bundle to pass along to the Fragment (may be null)
*/
protected void addTab(int titleRes, Class fragmentClass, Bundle args ) {
adapter.addTab( getString( titleRes ), fragmentClass, args );
}
/**
* Add a tab with a backing Fragment to the action bar
* #param titleRes A string to be used as the title for the tab
* #param fragmentClass The class of the Fragment to instantiate for this tab
* #param args An optional Bundle to pass along to the Fragment (may be null)
*/
protected void addTab(CharSequence title, Class fragmentClass, Bundle args ) {
adapter.addTab( title, fragmentClass, args );
}
My fragment TabFragmentMeasurement.class
public class TabFragmentMeasurement extends Fragment {
....... // Class' attributes
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
TextView txt = new TextView( inflater.getContext() );
....... // Change TextView's attributes
return txt;
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater)
{
inflater.inflate(R.menu.measurement, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.item_add_measurement:{
// Add a measurement
}
default:
return super.onOptionsItemSelected(item);
}
}
}
XML menu file measurement.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
<item
android:id="#+id/item_add_measurement"
android:icon="#android:drawable/ic_menu_add"
android:orderInCategory="1"
android:showAsAction="ifRoom"
android:title="#string/item_add_measurement"/>
</menu>
Why don't you extends SherlockFragment in the fragment classes??
Keep in mind that every context you pass like "this" should be followed by :
this.getSherlockActivity().
Related
It will be like 3 hours I try to update data from a activity to a fragment. I check all pages but it didn't work...
I have to made a BookManager. I have create some class to do it.
I have a main activity with two fragment, a first empty for the moment and a second with the summary of my list of book (most price of book, average...). When I want to add a book, I use a new activity and take data back after add the book (its work).
and I want to refresh the fragment after add the book.
Code of my main activity :
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private SimpleBookManager bookManager;
public final static int ADD_BOOK_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bookManager = new SimpleBookManager();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.button_add_menu) {
Intent intent = new Intent(MainActivity.this, AddBookActivity.class);
startActivityForResult(intent, ADD_BOOK_REQUEST);
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_BOOK_REQUEST) {
// On vérifie aussi que l'opération s'est bien déroulée
if (resultCode == RESULT_OK) {
// On affiche le bouton qui a été choisi
String[] valueBook = data.getStringArrayExtra("VALUE");
Book book = this.bookManager.createBook();
book.setTitle(valueBook[0]);
book.setAuthor(valueBook[1]);
book.setCourse(valueBook[2]);
book.setIsbm(valueBook[3]);
book.setPrice((int) Integer.parseInt(valueBook[4]));
}
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return PlaceholderFragment.newInstance(position + 1);
case 1:
Fragment frag = SummaryFragment.newInstance(bookManager);
return frag;
}
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "COLLECTION";
case 1:
return "SUMMARY";
}
return null;
}
}
In the method onActivityResult, I add the book and I want here to refresh or eventuelly when I'm back to the summary fragment. I tried with a FragmentTransaction, but the commit didn't work, because I don't have a tag to get my fragment (I don't know how it works to get one)... And the we don't have instance of the fragment because we use a static method to create it.
Code of my fragment :
public class SummaryFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String BOOKMANAGER = "book";
// TODO: Rename and change types of parameters
private String[] info;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment SummaryFragment.
*/
// TODO: Rename and change types and number of parameters
public static SummaryFragment newInstance(SimpleBookManager bookManager) {
String[] info = new String[5];
info[0] = String.valueOf(bookManager.count());
info[1] = String.valueOf(bookManager.getTotalCost());
info[2] = String.valueOf(bookManager.getMaxPrice());
info[3] = String.valueOf(bookManager.getMinPrice());
info[4] = String.valueOf(bookManager.getMeanPrice());
SummaryFragment fragment = new SummaryFragment();
Bundle args = new Bundle();
args.putStringArray(BOOKMANAGER, info);
fragment.setArguments(args);
return fragment;
}
public SummaryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.info = getArguments().getStringArray(BOOKMANAGER);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView;
TextView textView;
rootView = inflater.inflate(R.layout.fragment_summary, container, false);
textView = (TextView) rootView.findViewById(R.id.nbbook_value);
textView.setText(this.info[0]);
textView = (TextView) rootView.findViewById(R.id.totalcost_value);
textView.setText(this.info[1] + " SEK");
textView = (TextView) rootView.findViewById(R.id.mostprice_value);
textView.setText(this.info[2] + " SEK");
textView = (TextView) rootView.findViewById(R.id.leastprice_value);
textView.setText(this.info[3] + " SEK");
textView = (TextView) rootView.findViewById(R.id.averageprice_value);
textView.setText(this.info[4] + " SEK");
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
if (context instanceof Activity){
a=(Activity) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
You can get the Fragment instance by calling FragmentPagerAdapter's getItem method.
SummaryFragment frag = (SummaryFragment) mSectionsPagerAdapter.getItem(1);
And then call a method in the Fragment instance to refresh display, make sure to check null before calling method on the Fragment.
if (frag != null) {
frag.refreshBook(book);
}
I'm trying to create an application using the Master/Detail Flow template provided by Android.
I'm trying to add multiple actionbar menu items to both the master and detail portions of the actionbar.
I have use the example of Android studio but when i set the different menu for master e for detail, is show only the menu (to right) .
the Activity detail is:
public class PDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p_detail);
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(PDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(PatientDetailFragment.ARG_ITEM_ID));
PatientDetailFragment fragment = new PDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().add(R.id.p_detail_container, fragment).commit();
}
}
#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_p_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, PListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
the fragment detail is:
public class PDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private PObj mItem;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((PatientDetailActivity)getActivity()).getSupportActionBar().setTitle("Detail");
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = PListFragment.pObjHashMap.get(getArguments().getString(ARG_ITEM_ID));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_p_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.p_detail)).setText(mItem.name);
}
return rootView;
}
}
The activity master:
public class PListActivity extends BaseActivity implements PListFragment.Callbacks {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p_list);
// Show the Up button in the action bar.
// getActionBar().setDisplayHomeAsUpEnabled(true);
if (findViewById(R.id.p_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((PListFragment) getSupportFragmentManager()
.findFragmentById(R.id.p_list))
.setActivateOnItemClick(true);
}
// TODO: If exposing deep links into your app, handle intents here.
}
#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_p, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
// navigateUpFromSameTask(this);
SharedPreferenceObj sp = MySharedPref.getSharedPref(getApplicationContext());
sp.setLast_id_office(StaticValues.ID);
MySharedPref.setSharedPref(getApplicationContext(), sp);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Callback method from {#link PListFragment.Callbacks}
* indicating that the item with the given ID was selected.
*/
#Override
public void onItemSelected(String id) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(PatientDetailFragment.ARG_ITEM_ID, id);
PatientDetailFragment fragment = new PDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.p_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent dIntent = new Intent(this, PDetailActivity.class);
dIntent.putExtra(PDetailFragment.ARG_ITEM_ID, id);
startActivity(dIntent);
}
}
#Override
public void onBackPressed() {
SharedPreferenceObj sp = MySharedPref.getSharedPref(getApplicationContext());
sp.setLast_id_office(StaticValues.ID);
MySharedPref.setSharedPref(getApplicationContext(),sp);
super.onBackPressed();
}
}
the fragment master is:
public class PListFragment extends ListFragment {
//DummyContent dummyContent ;
public static List<PObj> pObjArrayList = new ArrayList<PObj>();
public static Map<String, PObj> pObjHashMap = new HashMap<String, PObj>();
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(String id);
}
/**
* A dummy implementation of the {#link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
#Override
public void onItemSelected(String id) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((PListActivity)getActivity()).getSupportActionBar().setTitle("Master");
pObjArrayList.clear();
pObjHashMap.clear();
for (int i=0;i<10;i++) {
patientObjArrayList.add(new PObj(i+"","name"+i,"address"+i));
patientObjHashMap.put(i+"",new PObj(i+"","name"+i,"address"+i));
}
setListAdapter(new ArrayAdapter<PObj>(getActivity(), android.R.layout.simple_list_item_activated_1,
android.R.id.text1, patientObjArrayList));
// TODO: replace with a real list adapter.
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = (Activity) context;
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(pObjArrayList.get(position).id);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
}
The problem is that i show only one menu (master) and no the menu (detail)
in this screenshot
in this screenshot I have only one menu and the + is on the right instead of the left next to the title "Master".
In the part relating to the detail is missing from the title and even the symbol X.
how can fix my problem?
I'm trying to show the action bar icons using FragmentActivity (with implements ActionBar.TabListener). I'm following this example : http://developer.android.com/training/implementing-navigation/lateral.html#tabs (EffectiveNavigation.zip) but i can't figure out how can i show the "search icon" (in my case) on the action bar, because for the moment i can only see the search option when tap the menu button.
jpg
I've tried to switch from FragmentActivity to ActionBarActivity but seems it does not support the ActionBar.TabListener.
MainActivity
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* three primary sections of the app. We use a {#link android.support.v4.app.FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
/**
* The {#link ViewPager} that will display the three primary sections of the app, one at a
* time.
*/
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
} else if(id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.demo_collection_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
startActivity(intent);
}
});
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create an intent that asks the user to pick a photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
// the application from the device home screen does not return
// to the external activity.
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
return rootView;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
menu_main.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=".MainActivity">
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/search_icon"
android:title="#string/action_search"
app:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.effectivenavigation" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CollectionDemoActivity"
android:label="CollectionDemo"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar">
</activity>
</application>
</manifest>
Try changing app:showAsAction="ifRoom" to android:showAsAction="always" for the search icon. The custom namespace only needs to be used if you are using the v7 support library, which does not seem to be the case. With that in mind, you should also change the namespace for your other menu item.
I just took the sample code shared by developer android site. I wanted to create a tabbed menu along with the option menu in the action bar. I want my activity to have the navigation tabs along with the action bar menu. I am not getting the action bar menu. But i have seen the applications which have navigation tabs as well as the action bar menu items as well. Please if someone helps me that would be of great help.
MainActivity Class
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
/**
* The {#link ViewPager} that will display the three primary sections of the app, one at a
* time.
*/
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(true);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.template_actvity, menu);
Toast.makeText(getApplicationContext(), "Indie onCreateOptionsMenu", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.demo_collection_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
startActivity(intent);
}
});
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create an intent that asks the user to pick a photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
// the application from the device home screen does not return
// to the external activity.
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
return rootView;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Activity_main XML File
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
template_activity 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">
<item
android:id="#+id/addTemplate"
android:orderInCategory="100"
android:icon="#drawable/ic_action_new"
android:title="Add Template"
app:showAsAction="always"/>
Here are some things to try:
I assume that in your template_activity.xml you remembered to include the </menu> tag? (You might have only missed copying+pasting it into your question).
Try using this code in your activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.template_activity, menu);
return true;
}
Note: You may also have a possible typo in your getMenuInflater().inflate(R.menu.template_actvity, menu); line. Specifically, you misspelled "activity".
Edit: Try the following XML for your menu XML file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<item
android:id="#+id/addTemplate"
android:orderInCategory="1"
android:icon="#drawable/ic_action_new"
android:title="Add Template"
android:showAsAction="always"/>
</menu>
As for getting the "three dot" overflow button, I realize now that you are using a device with a built-in menu button. It is intentional that devices with these don't include the overflow buttons. However, if you still want to implement this, you can read more about it here.
What i am trying to do ::
I want header for a certain set of rows one after another
What i am using:: Sticky Header( i am running this sample)
What is happening::
Project runs well but when i scroll the header goes and sits on top until the next header comes
Question:: (Disabling pinned header & enable the header scroll along with grid)
I want to disable this feature so that the header scrolls along with
gridview being scrolled instead of waiting for the next header
I have seen this feature possible in expandable listview but how to
implement this here
ItemDetailFragment.java
public class ItemDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private int mItem;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = getArguments().getInt(ARG_ITEM_ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail, container, false);
((TextView) rootView.findViewById(R.id.item_detail)).setText(getResources().getStringArray(R.array.countries)[mItem]);
return rootView;
}
}
ItemListActivity.java
public class ItemListActivity extends ActionBarActivity implements ItemListFragment.Callbacks {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
/**
* Callback method from {#link ItemListFragment.Callbacks} indicating that
* the item with the given ID was selected.
*/
#Override
public void onItemSelected(int id) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putInt(ItemDetailFragment.ARG_ITEM_ID, id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((ItemListFragment) getSupportFragmentManager().findFragmentById(R.id.item_list)).setActivateOnItemClick(true);
}
// TODO: If exposing deep links into your app, handle intents here.
}
}
ItemListFragment.java
public class ItemListFragment extends Fragment implements OnItemClickListener,
OnHeaderClickListener, OnHeaderLongClickListener {
private static final String KEY_LIST_POSITION = "key_list_position";
/**
* A dummy implementation of the {#link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
#Override
public void onItemSelected(int id) {
}
};
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
private int mFirstVisible;
private GridView mGridView;
private Menu mMenu;
private Toast mToast;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemListFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks)activity;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_item_list, menu);
mMenu = menu;
menu.findItem(R.id.menu_toggle_sticky).setChecked(
((StickyGridHeadersGridView)mGridView).areHeadersSticky());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_item_grid, container, false);
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
#Override
public void onHeaderClick(AdapterView<?> parent, View view, long id) {
String text = "Header " + ((TextView)view.findViewById(android.R.id.text1)).getText() + " was tapped.";
if (mToast == null) {
mToast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
} else {
mToast.setText(text);
}
mToast.show();
}
#Override
public boolean onHeaderLongClick(AdapterView<?> parent, View view, long id) {
String text = "Header " + ((TextView)view.findViewById(android.R.id.text1)).getText() + " was long pressed.";
if (mToast == null) {
mToast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
} else {
mToast.setText(text);
}
mToast.show();
return true;
}
#Override
public void onItemClick(AdapterView<?> gridView, View view, int position, long id) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(position);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_toggle_sticky:
item.setChecked(!item.isChecked());
((StickyGridHeadersGridView)mGridView)
.setAreHeadersSticky(!((StickyGridHeadersGridView)mGridView)
.areHeadersSticky());
return true;
case R.id.menu_use_list_adapter:
mGridView.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.item,
getResources().getStringArray(R.array.countries)));
mMenu.findItem(R.id.menu_use_list_adapter).setVisible(false);
mMenu.findItem(R.id.menu_use_sticky_adapter).setVisible(true);
mMenu.findItem(R.id.menu_toggle_sticky).setVisible(false);
return true;
case R.id.menu_use_sticky_adapter:
mGridView.setAdapter(new StickyGridHeadersSimpleArrayAdapter<String>(getActivity()
.getApplicationContext(), getResources().getStringArray(R.array.countries),
R.layout.header, R.layout.item));
mMenu.findItem(R.id.menu_use_list_adapter).setVisible(true);
mMenu.findItem(R.id.menu_toggle_sticky).setVisible(true);
mMenu.findItem(R.id.menu_use_sticky_adapter).setVisible(false);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mGridView = (GridView)view.findViewById(R.id.asset_grid);
mGridView.setOnItemClickListener(this);
/*
* Currently set in the XML layout, but this is how you would do it in
* your code.
*/
// mGridView.setColumnWidth((int) calculatePixelsFromDips(100));
// mGridView.setNumColumns(StickyGridHeadersGridView.AUTO_FIT);
mGridView.setAdapter(new StickyGridHeadersSimpleArrayAdapter<String>(getActivity()
.getApplicationContext(), getResources().getStringArray(R.array.countries),
R.layout.header, R.layout.item));
if (savedInstanceState != null) {
mFirstVisible = savedInstanceState.getInt(KEY_LIST_POSITION);
}
mGridView.setSelection(mFirstVisible);
// Restore the previously serialized activated item position.
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
((StickyGridHeadersGridView)mGridView).setOnHeaderClickListener(this);
((StickyGridHeadersGridView)mGridView).setOnHeaderLongClickListener(this);
setHasOptionsMenu(true);
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mGridView.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
}
#SuppressLint("NewApi")
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
mGridView.setItemChecked(mActivatedPosition, false);
} else {
mGridView.setItemChecked(position, true);
}
mActivatedPosition = position;
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(int position);
}
}
ItemDetailActivity.java
public class ItemDetailActivity extends ActionBarActivity {
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putInt(ItemDetailFragment.ARG_ITEM_ID,
getIntent().getIntExtra(ItemDetailFragment.ARG_ITEM_ID, 0));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment).commit();
}
}
}
You can make the headers scroll with your view by adding the following to your code:
mGridView.setAreHeadersSticky(false);
Hope this helps.