I saw a code here. Also shown below:
I'm in bit confused in Fragment fragment = new DemoObjectFragment(); where public static class DemoObjectFragment extends Fragment is a static class. So how we can call fragment.setArguments(args);
public class CollectionDemoActivity extends FragmentActivity {
// When requested, this adapter returns a DemoObjectFragment,
// representing an object in the collection.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
I created a base class for using fragments. I don't know if that will work for you. In a base class you can put information that's the same for all fragments. In my case a want to use a shared view model in all fragments. So I put the shared view model in the base class :
/**
* base class for the application
*/
public abstract class BaseFragment extends Fragment {
// use shared view model for exchanging information between fragments.
SharedViewModel sharedViewModel;
/**
* this function creates view and shared view model
* #param inflater - inflater creates the view
* #param container - container with views
* #param savedInstanceState - for saving state
* #return - return view
*/
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
// call base class first
super.onCreateView(inflater, container, savedInstanceState);
// then create view
View fragView = inflater.inflate(getFragment(), container, false);
// get shared view model.
sharedViewModel = new
ViewModelProvider(requireActivity()).get(SharedViewModel.class);
// inject fragment depended code
createView(fragView);
// return created view
return fragView;
}
/**
* get fragment
* (override in fragments and return xml layout name)
*/
protected abstract int getFragment();
/**
* inject fragment depended code while creating the view
* (override in fragments with fragment depended code)
*/
protected abstract void createView(View fragView);
}
Related
I have a Main fragment/ViewPager fragment inside the Main Activity and the Main Fragment has the Viewpager2 where I add child fragments into ViewPager via Adapter. Earlier I had a method in Main Activity (Which also had view pager)
public void ChangeFragment_ViewPager(int position, boolean outside) {
if (viewPager!=null){
viewPager.setCurrentItem(position);
}
}
This method easily changes the fragment when I call from any child fragment of viewpager but since I shifted the viewpager to the Main fragment, my viewpager always comes out null from child.
MainFragment.newInstance().ChangeFragment_ViewPager(0, false);
The Main Fragment
public class MainFragment extends Fragment {
ViewPager2 viewPager;
public MainFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.main_fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = view.findViewById(R.id.Navigation_Drawer_ViewPager);
TabAdapter tabAdapter = new TabAdapter(getChildFragmentManager(), getLifecycle());
viewPager.setAdapter(tabAdapter);
}
public void ChangeFragment_ViewPager(int position, boolean outside) {
if (viewPager!=null){
viewPager.setCurrentItem(position);
}
}
Tab Adapter
public class TabAdapter extends FragmentStateAdapter {
String TAG="###TAB ADAPTER###";
public TabAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
Log.d(TAG, "Fragment 1");
return FriendsList.newInstance();
case 1:
Log.d(TAG, "Fragment 2");
return PPL_main.newInstance();
}
return FriendsList.newInstance();
}
#Override
public int getItemCount() {
return 2;
}
}
How can I change the fragment from any ViewPager's child fragment?
MainFragment.newInstance().ChangeFragment_ViewPager(0,false);
This line of code instantiates a brand new instance of MainFragment; and therefore you found a null ViewPager.
Instead of that, the current instance exist in the fragment manager is required or simply use requireParentFragment() from the ViewPager child page fragment to get the MainFragment that hosts the ViewPager:
((MainFragment) requireParentFragment()).ChangeFragment_ViewPager(0, false);
I have an app with 4 tabs, all are Fragments and have an adapter because I'm using RecyclerView. On the first tab I have items. I want the second tab to show the items that are checked on the first and listen to the changes. The 3rd tab shows the items from the 2nd tab (=1st tab checked items) when I click on a button on the first segment. Now I set the listeners in onCreate and onCreateView. Sometimes it's working, sometimes not. My suspicion is that the create methods aren't executed in the same order every time. The other problem is that sometimes my Fragment has to notify the listener, sometimes the the Fragment's adapter. How do I treat it nicely?
First tab (it's adapter will notify)
public class EventFragment extends Fragment implements BettingEventAdapter.BettingItemClickListener {
private RecyclerView recyclerView;
static private BettingEventAdapter adapter;
private BettingListDatabase database;
private static Answer bettingData = null;
private static final String TAG = "EVENT";
private static BettingEventAdapter.BettingItemClickListener listener;
public static void setListener(BettingEventAdapter.BettingItemClickListener _listener) {
listener = _listener;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = BettingListDatabase.getInstance(this.getContext());
loadBettingData();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events,
container, false);
recyclerView = view.findViewById(R.id.MainRecyclerView);
adapter = new BettingEventAdapter(this);
adapter.addBettingItemListener(listener);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getBaseContext()));
recyclerView.setAdapter(adapter);
loadItemsInBackground();
return view;
}
Second tab:
public class TicketFragment extends Fragment implements BettingEventAdapter.BettingItemClickListener {
private RecyclerView recyclerView;
TextView prizeTextView;
EditText stakeInput;
Button bSave;
private static BettingTicketAdapter.TicketSaveClickListener listener;
private BettingListDatabase database;
private BettingTicketAdapter adapter;
double odds=1;
int stake=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = BettingListDatabase.getInstance(this.getContext());
EventFragment.setListener(this);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ticket,
container, false);
recyclerView = view.findViewById(R.id.TicketRecyclerView);
adapter = new BettingTicketAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getBaseContext()));
recyclerView.setAdapter(adapter);
}
Third tab:
public class TicketListFragment extends Fragment implements BettingTicketAdapter.TicketSaveClickListener {
private BettingTicketListAdapter parentAdapter;
private BettingListDatabase database;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = BettingListDatabase.getInstance(this.getContext());
TicketFragment.setListener(this);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_ticket_list,
container, false);
RecyclerView parentRecyclerView = view.findViewById(R.id.SavedTicketParentRecyclerView);
parentAdapter = new BettingTicketListAdapter();
//TODO db-ből feltölteni
loadItemsInBackground();
parentRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getBaseContext()));
parentRecyclerView.setAdapter(parentAdapter);
return view;
}
Pager activity:
public class PagerActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager);
}
#Override
protected void onResume() {
super.onResume();
ViewPager mainViewPager = findViewById(R.id.mainViewPager);
TabPagerAdapter tabPagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), this);
mainViewPager.setAdapter(tabPagerAdapter);
}
}
https://developer.android.com/training/basics/fragments/communicating
To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.
Here is an example for your Fragment:
EventFragment
public class EventFragment extends Fragment {
OnEventSelectedListener callback;
public void setOnEventSelectedListener(OnEventSelectedListener callback) {
this.callback = callback;
}
// This interface can be implemented by the Activity, parent Fragment,
// or a separate test implementation.
public interface OnEventSelectedListener {
public void onEventSelected(int position);
}
// ...
}
PagerActivity
public class PagerActivity extends AppCompatActivity implements EventFragment.OnEventSelectedListener{
// ...
// In order to receive event callbacks from the fragment, the activity that
// hosts it must implement the interface defined in the fragment class.
//For example, the following activity implements the interface from the above example.
public void onEventSelected(int position) {
// ...
}
#Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof EventFragment) {
EventFragment eventFragment = (EventFragment) fragment;
eventFragment.setOnEventSelectedListener(this);
}
}
}
For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
callback.onEventSelected(position);
}
How would I set up my code so when I start the tabactivity it opens to a specific tab depending on what intents I started it from?
ie. click a squat button from mainactivity -> opens tabactivity with squat-tab selected and showing
Most googling resulted in people using tabhost so I don't know what I can do here.
Thanks
public class tabtry extends Activity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v13.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.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabtry);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.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 callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tabtry, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#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 onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link android.support.v13.app.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).
//return PlaceholderFragment.newInstance(position + 1);
switch (position) {
case 0:
return PlaceholderFragment.newInstance(position + 1);
case 1:
return Squat.newInstance(position + 1);
case 2:
return Dead.newInstance(position + 1);
case 3:
return Press.newInstance(position + 1);
case 4:
return Clean.newInstance(position + 1);
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section5).toUpperCase(l);
case 1:
return getString(R.string.title_section6).toUpperCase(l);
case 2:
return getString(R.string.title_section7).toUpperCase(l);
case 3:
return getString(R.string.title_section8).toUpperCase(l);
case 4:
return getString(R.string.title_section9).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.benchtab, container, false);
return android;
}
}
public static class Squat extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Squat newInstance(int sectionNumber) {
Squat fragment = new Squat();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public Squat() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.squattabtry, container, false);
return rootView;
}
}
public static class Dead extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Dead newInstance(int sectionNumber) {
Dead fragment = new Dead();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public Dead() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.deadtab, container, false);
return rootView;
}
}
public static class Press extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Press newInstance(int sectionNumber) {
Press fragment = new Press();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public Press() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.presstab, container, false);
return rootView;
}
}
public static class Clean extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Clean newInstance(int sectionNumber) {
Clean fragment = new Clean();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public Clean() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.powertab, container, false);
//powerStat = (EditText)rootView.findViewById(R.id.powerstat_id);
//powerreps = (EditText)rootView.findViewById(R.id.powerrepstat_id);
return rootView;
}
}
}
setSelectedNavigationItem is what your looking for.
you'll have to pass something extra or use the intent action what ever your comfortable with in passing data to an activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// position is zero based tab.
int position = 0;
Intent intent = getIntent();
String intentaction = intent.getAction();
if (intentaction != null) {
if (intentaction.equals("hello world")) {
position = 2;
}
}
actionbar.setSelectedNavigationItem(position);
Here is my the problem, I have an activity, which includes a Fragment that has a ViewPager using (FragmentStatePagerAdapter), all works perfect when the Activity loads for the first time, but when setting setRetainInstance(true) to the parent fragment (the one with the pager), and orientation changes on the activity, it causes
java.lang.IllegalStateException: No activity
When trying to add the saved fragment, here is the code:
Activity:
public class DetailActivity{
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame_layout_with_progress_container);
...
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
FragmentManager fm = getSupportFragmentManager();
if (savedInstanceState != null) {
Fragment f = fm.findFragmentById(R.id.container);
if(f instanceof DetailPagerFragment){
detailPagerFragment = (DetailPagerFragment) f;
}
}
}
#Override
protected void onPostResume() {
super.onPostResume();
//If fragment is null, create a new instance
if(detailPagerFragment==null){
detailPagerFragment =
DetailContainerFragment.newInstance(details, initialPosition);
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, detailPagerFragment);
ft.commit();
}
Note: that i have to save the fragment instance on onCreate because when the code reaches onStart the reference for this fragment was null (this issue is not important for the time it has something to do with the NavigationDrawer), so i need to manually save the instance of the fragment.
Activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"/>
</RelativeLayout>
ViewPager Fragmentm this class extends for DetailPagerFragment which is a custom pager fragment it only wraps common code for pagers (for example view inflation, uses inflateView method), this is why the pager is added on a fragment instead of directly to the activity:
public class DetailContainerFragment extends DetailPagerFragment {
List<Detail> details;
public static DetailContainerFragment newInstance(List<Detail> details,int selectedPosition) {
DetailContainerFragment df = new DetailContainerFragment();
df.setSelectedPosition(selectedPosition);
df.setDetails(details);
return df;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
/**
* Inflates the view to be used by this fragment
*
* #param inflater
* Inflater to use
* #return Inflated view
*/
#Override
public View inflateView(LayoutInflater inflater) {
return inflater.inflate(R.layout.detail_pager_fragment, null);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
DetailStatePagerAdapter detailStatePagerAdapter = new DetailStatePagerAdapter(getChildFragmentManager());
setPagerAdapter(detailStatePagerAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
private class DetailStatePagerAdapter extends FragmentStatePagerAdapter {
public DetailStatePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return DetailFragment.newInstance(details.get(position));
}
#Override
public CharSequence getPageTitle(int position) {
return details.get(position).getTitle();
}
#Override
public int getCount() {
return details.size();
}
}
}
I had a similar problem with child fragments in a ViewPager.
The parent fragment created new instances of the child fragments to be used with the ViewPager while the adapter kept instances of the old child fragments used before the configuration change.
I ended up cleaning the ChildFragmentManager before initializing the adapter with it:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPager = (ViewPager) view.findViewById(R.id.pager);
cleanChildFragments(getChildFragmentManager());
mPagerAdapter = new MyPagerAdapter(getChildFragmentManager(), getTabFragments());
mPager.setAdapter(mPagerAdapter);
}
/**
* This is necessary to have a clean ChildFragmentManager, old fragments might be called otherwise
* #param childFragmentManager
*/
private void cleanChildFragments(FragmentManager childFragmentManager) {
List<Fragment> childFragments = childFragmentManager.getFragments();
if (childFragments != null && !childFragments.isEmpty()) {
FragmentTransaction ft = childFragmentManager.beginTransaction();
for (Fragment fragment : childFragments) {
ft.remove(fragment);
}
ft.commit();
}
}
Maybe this helps someone...
I'm new to software development and java as a whole, I've been trying for days now to get the default template android gives for fixed tabbed Navigation with pageviewer. Regardless of what I try I can't seem to get it to load anything but the first fragment. all the other onClick tabs events in the Emulator load the very same first fragment defined in the template, sliding the pager has the same effect.
I've tried modifying my code several times till the point where there are little runtime errors, but I still can't get it to load other fragments through the Tabs.
I'd appreciate any help with this.
here's my code.
My projects a Native tablet EHR App
package com.example.medictouch;
import java.util.Locale;
import com.example.medictouch.MedicTouchActivity.encountersFragment;
import com.example.medictouch.MedicTouchActivity.patient_chartFragment;
import com.example.medictouch.MedicTouchActivity.billingFragment;
import com.example.medictouch.MedicTouchActivity.medicationsFragment;
import com.example.medictouch.MedicTouchActivity.treatmentsFragment;
import com.example.medictouch.MedicTouchActivity.laboratoryFragment;
import com.example.medictouch.MedicTouchActivity.imagingFragment;
import com.example.medictouch.MedicTouchActivity.doctors_notesFragment;
import com.example.medictouch.MedicTouchActivity.departmentsFragment;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MedicTouchActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. 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}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.medictouch);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.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 callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* 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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new encountersFragment();
Fragment fragment1 = new patient_chartFragment();
Fragment fragment2 = new billingFragment();
Fragment fragment3 = new medicationsFragment();
Fragment fragment4 = new treatmentsFragment();
Fragment fragment5 = new laboratoryFragment();
Fragment fragment6 = new imagingFragment();
Fragment fragment7 = new doctors_notesFragment();
Fragment fragment8 = new departmentsFragment();
return fragment;
}
#Override
public int getCount() {
// Show 6 total pages.
return 10;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toLowerCase();
case 1:
return getString(R.string.title_section2).toLowerCase();
case 2:
return getString(R.string.title_section3).toLowerCase();
case 3:
return getString(R.string.title_section4).toLowerCase();
case 4:
return getString(R.string.title_section5).toLowerCase();
case 5:
return getString(R.string.title_section6).toLowerCase();
case 6:
return getString(R.string.title_section7).toLowerCase();
case 7:
return getString(R.string.title_section8).toLowerCase();
case 8:
return getString(R.string.title_section9).toLowerCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public class encountersFragment extends Fragment {
private final int title_section1 = 0;
public final int ARG_SECTION_NUMBER = title_section1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.encounters,
container, false);
return rootView;
}
}
public class patient_chartFragment extends Fragment {
private final int title_section2 = 1;
public final int ARG_SECTION_NUMBER = title_section2;
public patient_chartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.patient_chart,
container, false);
return rootView;
}
}
public class billingFragment extends Fragment {
private final int title_section3 = 2;
public final int ARG_SECTION_NUMBER = title_section3;
public billingFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.billing,
container, false);
return rootView;
}
}
public class medicationsFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 3;
public medicationsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.medications,
container, false);
return rootView;
}
}
public class treatmentsFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 4;
public treatmentsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.treatments,
container, false);
return rootView;
}
}
public class laboratoryFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 5;
public laboratoryFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.labs,
container, false);
return rootView;
}
}
public class imagingFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 6;
public imagingFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.imaging,
container, false);
return rootView;
}
}
public class doctors_notesFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 7;
public doctors_notesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.doctors_notes,
container, false);
return rootView;
}
}
public class departmentsFragment extends Fragment {
public final int ARG_SECTION_NUMBER = 8;
public departmentsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.departments,
container, false);
return rootView;
}
}
}
You need to use switch..case.. block in getItem(int position) method. Use below code.
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment;
switch (position) {
case 0:
fragment = new encountersFragment();
break;
case 1:
fragment = new patient_chartFragment();
break;
case 2:
fragment = new billingFragment();
break;
case 3:
fragment = new medicationsFragment();
break;
case 4:
fragment = new treatmentsFragment();
break;
case 5:
fragment = new laboratoryFragment();
break;
case 6:
fragment = new imagingFragment();
break;
case 7:
fragment = new doctors_notesFragment();
break;
case 8:
fragment = new departmentsFragment();
break;
default:
break;
}
return fragment;
}
Edit:
I found this error in your code(may have more errors). You are using AutoCompletTextView in xml change it to AutoCompleteTextView
08-16 21:53:46.247: E/AndroidRuntime(4768): Caused by:
java.lang.ClassNotFoundException: Didn't find class "android.view.AutoCompletTextView" on
path: DexPathList[[zip file "/data/app/com.example.medictouch-
2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.medictouch-2, /system/lib]]