I have built an Android application that uses tabs to navigate. I am using fragments for the majority of the application, however I need to display one activity. How do i display an activity in case 2. Below is the code i have at the moment, i know it returns a fragment but how do i enable the use of both?
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).
System.out.println("current position = " + position);
Fragment fragment = null;
switch(position){
case 0:
return new diaryFragment();
case 1:
return new newEntryFragment();
case 2:
return new Calendarnew();
}
return null;
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new diaryFragment();
break;
case 1:
fragment = new newEntryFragment();
case 2:
fragment = new Calendarnew();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
Hi I dont actually get what you are up to but try reading this, maybe it could somehow solve your issue. https://stackoverflow.com/a/2958586/4470313
Related
Originally I had a single fragment loaded in my MainActivityclass. I used the following in
onCreate
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(new TimeTableFragment(), TIMETABLEFRAGMENT_TAG)
.commit();
}
and in
onResume
if(*setting has changed*){
TimeTableFragment tf = (TimeTableFragment) getSupportFragmentManager()
.findFragmentByTag(TIMETABLEFRAGMENT_TAG);
if (null != tf) {
tf.onStudentIdChanged();
}
}
The onStudentIdChanged() method would refresh the fragment data as preference settings have changed.
I have now refactored this activity to use FragmentPagerAdapterand load two different fragments in tabs. Both fragments are instances of the same TimetableFragment class, but with different parameters passed when creating.
FragmentPagerAdapter methods
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a Fragment
switch (position) {
case 1:
case 2:
return TimeTableFragment.newInstance(position);
case 0:
//todo add the single day here
return TimeTableFragment.newInstance(position);
}
return null;
}
TimetableFragment Method
public static TimeTableFragment newInstance(int sectionNumber) {
TimeTableFragment fragment = new TimeTableFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
Now that this is working, in onResume of my MainActivityI am no longer able to access the Fragments using findFragmentByTag, as they are not added in this way during onCreateand I can no longer call the onStudentIdChanged method.
How, for all created instances of the Timetable Fragment can I call this method and have the data updated / refreshed?
In your FragmentPagerAdapter imprementation, add private SparseArray<Fragment> mFragments = new SparseArray<Fragment>();
Modify your getItem method as follows:
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a Fragment
Fragment fragment = null;
switch (position) {
case 1:
case 2:
fragment = mFragments.get(position);
if (fragment == null) {
fragment = TimeTableFragment.newInstance(position);
mFragments.append(position, fragment)
}
break;
case 0:
//todo add the single day here
fragment = mFragments.get(position);
if (fragment == null) {
fragment = TimeTableFragment.newInstance(position);
mFragments.append(position, fragment)
}
break;
}
return fragment;
}
Now when you can get instance of fragment by position.
My current implementation of FragmentStatePagerAdapter creates new fragments every time it is called by viewpager.
I Want to save states of fragments which are previously loaded and wnat to reuse them.
I think to achieve this I have to implement InstantiateItem but not clear how to?
This is my code for FragmentStatePagerAdapter
using System.Collections.Generic;
//using Android.App;
using Android.Views;
using Hollard.MLAM.Android.Fragments.Fna;
using Object = Java.Lang.Object;
using Android.Support.V4.App;
public FnaFragmentPagerAdapter(FragmentManager fm)
: base(fm)
{
_registeredFragments = new Dictionary<int, Fragment>();
}
public override Fragment GetItem(int position)
{
Fragment fragment = null;
switch ((FnaStep)position)
{
case FnaStep.First:
fragment = new FnaStep1Fragment();
break;
case FnaStep.Second:
fragment = new FnaStep2Fragment();
break;
case FnaStep.Third:
fragment = new FnaStep3Fragment();
break;
case FnaStep.Fourth:
fragment = new FnaStep4Fragment();
break;
case FnaStep.Fifth:
fragment = new FnaStep5Fragment();
break;
case FnaStep.Sixth:
fragment = new FnaStep6Fragment();
break;
default:
break;
}
return fragment;
}
public override int Count
{
get { return PageCount; }
}
public Fragment GetRegisteredFragment(ViewGroup container, int position)
{
global::Android.Support.V4.App.Fragment fragment = null;
if (!_registeredFragments.TryGetValue(position, out fragment))
{
InstantiateItem(container, position);
_registeredFragments.TryGetValue(position, out fragment);
}
return fragment;
}
}
public enum FnaStep
{
First = 0,
Second,
Third,
Fourth,
Fifth,
Sixth
}
}
Please help me How to implement FragmentStatePagerAdapter, so it can reuse fragments which are already created.
You should save instances of your fragments and not instantiate them each time. In other words, instead of this line
fragment = new FnaStep1Fragment();
you should use
fragment = _FnaStep1FragmentInstance;
such that _FnaStep1FragmentInstance was initialized in the constructor of the container activity.
I'm currently working with an application that has "swipey-tabs" and uses the following PagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new HomeFragment();
case 1:
return new ListFragment();
case 2:
return new ChartFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
I'm using the following code to communicate with one of my fragments from the main activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1)
{
if (resultCode == Activity.RESULT_OK)
{
String className = data.getExtras().getString("class_name");
if (className.trim().length() > 0) {
HomeFragment homeFrag = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.home_fragment);
if(homeFrag != null) {
Log.d("MainActivity", "homeFrag is not null");
homeFrag.newClass(className);
}else{
Log.d("MainActivity", "homeFrag is null");
HomeFragment newFragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.home_fragment, newFragment);
transaction.commit();
newFragment.newClass(className);
}
addSubjectToDataBase(className);
}
}
}
}
My problem is that when I try to communicate with the fragment from the main activity, I seem to get multiple fragments existing at the same time. When I change the orientation of the screen or restart the activity, I get the modified version of the fragment, but when I swipe back and forth to view the fragments, I get the old, non-modified version of the fragment. The fragment manager doesn't seem to be registering the fragments created by the adapter because though I know the fragments have been created, the fragment manager always returns a null home fragment.
How should I go about avoiding this problem, and what is the best way to communicate with the fragment from the main activity?
After reading through this post I worked out a solution to my own question. The problem was that since FragmentPagerAdapter manages its own fragments, the fragment that I was trying to access wasn't the same as the one being used by the view pager.
I worked out a way of accessing the tags of the fragments that are used by the view pager by modifying my modifying my PagerAdapter as such:
public class TabsPagerAdapter extends FragmentPagerAdapter {
protected String homeTag;
protected String listTag;
protected String chartTag;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
Log.d("Adapter", "returning new homeFragment");
return new HomeFragment();
case 1:
return new ListFragment();
case 2:
return new ChartFragment();
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
switch (position){
case 0:
homeTag = createdFragment.getTag();
break;
case 1:
listTag = createdFragment.getTag();
break;
case 2:
chartTag = createdFragment.getTag();
break;
}
return createdFragment;
}
public String getHomeTag(){
return homeTag;
}
public String getListTag(){
return listTag;
}
public String getChartTag(){
return chartTag;
}
#Override
public int getCount() {
return 3;
}
}
Then, it was a simple matter to modify my code to access the correct fragments after I had access the proper fragment tags:
HomeFragment homeFrag = (HomeFragment) getSupportFragmentManager().findFragmentByTag(mAdapter.getHomeTag());
if(homeFrag != null) {
Log.d("MainActivity", "homeFrag is not null");
homeFrag.newClass(className);
}else{
Log.d("MainActivity", "homeFrag is null");
HomeFragment newFragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, newFragment, madapter.get);
transaction.commit();
newFragment.newClass(className);
It's not elegant but I would do something like this (Maybe someone will post a better solution):
In a singleton, I'll put an array of fragment:
public static Fragment[] sShownFragments = new Fragment[3];
Then in the getItem() method:
if(SingletonClass.sShownFragments[index]!=null){
return mFragments[index];
}
switch (index) {
case 0:
SingletonClass.sShownFragments[index] = new HomeFragment();
break;
case 1:
SingletonClass.sShownFragments[index] = new ListFragment();
case 2:
SingletonClass.sShownFragments[index] = new ChartFragment();
default:
SingletonClass.sShownFragments[index] = new Fragment();
}
return SingletonClass.sShownFragments[index];
Then in the getCount():
return SingletonClass.sShownFragments.length();
Now in your onActivityResult():
\\some code ...
((HomeFragment)SingletonClass.sShownFragments[0]).newClass(className);
\\ some other code...
I'm using the native Android drawer for my menu, here in MainActivity :
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
//Home
fragment = new EntryFragment();
break;
case 1:
//Journal
fragment = new JournalFragment();
break;
case 2:
// Medications
fragment = new RxFragment();
break;
case 3:
// Reminders
fragment = new ReminderFragment();
break;
case 4:
// Counselor Locator
fragment = new LocatorFragment();
break;
case 5:
// Library
fragment = new LibraryFragment();
break;
case 6:
// Settings
break;
case 7:
// About
break;
default:
break;
}
if (fragment != null) {
fm.beginTransaction()
.replace(R.id.container, fragment).addToBackStack(String.valueOf(position)).commit();
String fragmentTitles[] = getResources().getStringArray(R.array.menu_array);
if(mActionBar != null) {
mActionBar.setTitle(fragmentTitles[position]);
}
} else {
Log.e("MainActivity", "Error in creating fragment");
}
But I'm repurposing EntryFragment for another activity (EntryDetailActivity), so in EntryFragment I defined a couple of methods to modify the view based on which activity is hosting it:
// Runs on the home page, shows/hides appropriate views
public void prepareForHomeView() {
mTxtDate.setVisibility(View.GONE);
mBtnDiffDay.setVisibility(View.GONE);
mEdtNotes.setVisibility(View.GONE);
mBtnSave.setVisibility(View.GONE);
mBtnDelete.setVisibility(View.GONE);
}
// Runs on the detail page, shows/hides appropriate views
public void prepareForDetailView() {
mBtnLog.setVisibility(View.GONE);
}
In EntryDetailActivity, I can easily call prepareForDetailView() in onResumeFragments(), but I'm having an issue of where to call prepareForHome() in MainActivity, since I am swapping fragments in and out based on the menu. Any suggestions?
/** Update **/
I assigned the fragments a tag that is the position of the menu through addToBackstack(). I also added the following method to my MainActivity:
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
FragmentManager fm = getSupportFragmentManager();
EntryFragment entryFrag = (EntryFragment)fm.findFragmentByTag("0");
if(entryFrag != null) {
Log.v("rx", "Home frag is not null");
} else {
Log.v("rx", "Home frag is null");
}
}
Activity (or FragmentActivity) has onAttachFragment(Fragment fragment) - you could do an instanceof on fragment to determine if it is the correct type of fragment (or use the id, tag, etc) and call the appropriate method.
Alternatively, you could have the Fragment check the getActivity() (in onCreateView / onViewCreated).
I have a section my class which is for handling what fragment to load for the FragmentPagerAdapter. Right now it loads fragments just fine but now I want to implement a FragmentActivity and I am having a problem figuring how to create it as I cant use "newinstance" since its type of Activity, and on top of it, I dont know how to call that FragmentActivity as its different from loading just a Fragment via "newinstance" method. My second tab is the one that I would like to be extended to FragmentActivity.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Context _context;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
_context= getApplicationContext();
}
#Override
public Fragment getItem(int i) {
Fragment f = new Fragment();
switch(i){
case 0:
f=News.newInstance(_context);
break;
case 1:
f=Info.newInstance(_context);
break;
case 2:
f=Files.newInstance(_context);
break;
case 3:
f=Donate.newInstance(_context);
break;
}
/*
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
*/
return f;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.title_section1).toUpperCase();
case 1: return getString(R.string.title_section2).toUpperCase();
case 2: return getString(R.string.title_section3).toUpperCase();
case 3: return getString(R.string.title_section4).toUpperCase();
}
return null;
}
}
My guess is that I cant use getitem methods as that for only switching Fragments and that I would have to use something like:
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_content, new BasicFragment());
ft.commit();
Can someone help point me in the right direction?
Can someone help point me in the right direction?
This is not supported. It certainly is not possible with FragmentPagerAdapter, which only works with fragments.