Implementing Tabs in Android - android

I like to check I am doing the right thing or is there a better way than this.
I like to implement tabs in Android application. I found out that I should use Fragment.
Then I implemented my application with TabbedActivity.Inside I added in Tabs.
I have added Tab in the onCreate() of the MainActivity as
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Accelerometer"));
tabLayout.addTab(tabLayout.newTab().setText("Gyroscope"));
// 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);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
Since I want to use two xmls for two different fragments (frangment1.xml and frangment2.xml), I created two blank fragments and inside PlaceholderFragment class's, I added frangment1.xml and frangment2.xml using cnt variable
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";
private static int cnt = 0;
public PlaceholderFragment() {
}
/**
* 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if(cnt== 0) {
rootView = inflater.inflate(R.layout.tab_fragment1, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.frag1);
cnt++;
}else if(cnt== 1){
rootView = inflater.inflate(R.layout.tab_fragment2, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.frag2);
}
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
I like to check is that the correct way or any other better way for that.

Hey there is not much to say about this code. I have not tried to run your code. But if it run for you its fine. Even I use to do this type of Tabs implementation in android. But since there are many changes from then as per the new android design library. There are tons of new features, not just in designs but also in functionalities. You might wanna check this link for some of them being implemented here.
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
Also for guidelines from google on tabs, their implementations, specifications and all that stuff check this out.
https://www.google.com/design/spec/components/tabs.html#tabs-usage

No this is not right.
You shouldn't make the two fragments inside one fragment. You should separate them to step out of the if condition in every method (checking which view is inflated). Suppose now you have two separate fragments, you just need to check the position in your adapter to choose which fragment you need in which position.
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new MyFragment1();
break;
case 1:
return new MyFragment2();
break;
}
return null;
}

Related

Access AutoComplete inside Fragment of Tab Layout

Following is my onCreate code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Inside Base Drawer...");
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.tab_layout);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager){
#Override
public void onTabSelected(TabLayout.Tab tab){
tabPosition = tab.getPosition();
}
});
}
And following is my FragmentPageAdapter, for sliding tab layouts
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Tab1Fragment tab1 = new Tab1Fragment();
return tab1;
case 1:
Tab1Fragment tab2 = new Tab2Fragment();
return tab2;
case 2:
Tab1Fragment tab3 = new Tab3Fragment();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
}
Following is the tabFragment code:
public class Tab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState){
return inflater.inflate(R.layout.tab_activity_sheet_details_tab1, viewGroup, false);
}
}
I have a custom autocompleteTextView inside the tab layout (tab_activity_sheet_details_tab1)
Following is the code for the same:
<com.example.user.package.TabLayoutActivity.AutoCompleteAdapter.HistoryAutoCompleteTextView
android:id="#+id/history_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapCharacters"
android:imeOptions="flagNoExtractUi|actionSearch"/>
However, I'm not being able to access this element from TabLayoutActivity. What is the best way to access this after the fragment view is inflated?
And do note that there are similar items in all the three Tab Layouts.
Is there a need of a separate adapter holding all the three fragment layouts and access them? If so, from which lifecycle element can I access them?
P.S.: I'm looking for a non-adapter access to fragments, if possible (possibly by "layout id")?
Something like this would expose the view to the outside world:
public class Tab1Fragment extends Fragment {
View mView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState){
mView = inflater.inflate(R.layout.tab_activity_sheet_details_tab1, viewGroup, false);
return mView;
}
public HistoryAutoCompleteTextView getTextView() {
return (HistoryAutoCompleteTextView)mView.findViewById(R.id.history_text);
}
}
Then you can get it from the fragment:
textView = ((Tab1Fragment)fragment).getTextView()
But from a software design point of view, you should probably not do that and consider instead managing this view entirely in the Fragment and only expose the data collected.

How to send data between fragments in Android?

I'm trying to make an Android app with a tabbed form. One tab for Autonomous, and the other for TeleOp.
The TeleOp tab needs to be able to read data from the Autonomous tab, but I'm having trouble passing data from one to the other, while I'm switching from the first tab to the next.
They're both fragments, with one parent, called the Match Form. I'm not entirely sure what to do, so here is my code:
MatchForm.java
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public TabLayout tabLayout;
public static String startingPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_form);
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) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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_match_form, 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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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";
public PlaceholderFragment() {
}
/**
* 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_match_form, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* 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) {
switch(position){
case 0:
AutonomousFragment autonomousFragment = new AutonomousFragment();
return autonomousFragment;
case 1:
TeleopFragment teleopFragment = new TeleopFragment();
return teleopFragment;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
public void easyToast(String text){
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
AutonomousFragment.java
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
sendData();
}
}
}
public void sendData(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
TeleopFragment teleopFragment = new TeleopFragment();
ft.add(R.id.container, teleopFragment);
final Bundle args = new Bundle();
args.putString("startingPos", startingPos);
args.putString("switchPos", switchPos);
args.putString("scalePos", scalePos);
args.putString("autoRun", autoRun);
args.putString("allianceColor", selectedAllianceColor);
teleopFragment.setArguments(args);
ft.commit();
}
TeleopFragment.java
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.teleop_fragment, container, false);
final Bundle bundle = getArguments();
button = (Button)view.findViewById(R.id.submitButton);
if(bundle != null && bundle.containsKey("startingPos")){
startingPos = bundle.getString("startingPos");
easyToast(startingPos);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
easyToast(startingPos);
}
});
return view;
}
There are many ways to pass the data.One easy and efficient way to implement.create a public class in your package.In that class declare your values as static.
public class MyDataClass {
public static String value1;
public static String value2;
}
Now you can access these values from anywhere either in the fragment or activity.
you can pass the values like this
MyDataClass myobj=new MyDataClass();
myobj.value1="Hello";
To fetch the value in another class use
String val=myobj.value1;
You can pass the data from Autonomous Fragment to the parent activity first and then pass it to the Teleop Fragment.
You can use Intents for this.
How to pass values between Fragments
Or use a custom listener to notify the other fragment once the data is sent.
1. Do you really need ViewPager here?
ViewPager is needed if you want to display multiple fragments at the same time. On my opinion, the fragments in ViewPager must be equal and independent. If you want to keep communication between Fragments in ViewPager you can:
Use EventBus or LocalBroadcastManager, etc.;
Cache Fragment inside ViewPager in this way
2. Maybe you need flow?
If you want implement some fragment flow, for example "PickGoods" -> "GoodsCheckout", it is better to use fragment transactions and pass arguments with Bundle. For example, pass selected goods ids from "PickGoods" to "GoodsCheckout".
Note. You can't pass really big amount of data. But it is enough for large set of ids.
3. One more solution.
If your flow belongs to separate activity, which is going to be killed, after final action in flow (it is important to avoid memory leaks) you can use ViewModel attached to activity and store data in it. You can get ViewModels attached to activity from its fragments:
ViewModelProviders.of(getActivity()).get(DataViewModel.class);

android-viewpager with multiple sub-fragments in each tab

This is giving me headache. Lets say my app has a ViewPager which contains 4 tabs. I want to have multiple sub-fragments within each tab. that means each tab would have more than just one view. I totally have no clue how to achieve this....
I have a FragmentActivity which gets load first and set my ViewPager
public class FragActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new FFNPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOffscreenPageLimit(3);
tabs.setViewPager(pager);
}
}
I then have my FragmentPagerAdapter
public class PagerAdapter extends FragmentPagerAdapter implements TextAndIconTabProvider {
private final String[] TITLES = { "FIRST", "SECOND", "THIRD", "FORTH" };
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment frag = new Fragment();
switch (position) {
case 1:
frag = new FirstFrag();
break;
case 2:
frag = new SecondFrag();
break;
case 3:
frag = new ThirdFrag();
break;
case 4:
frag = new ForthFrag();
break;
}
return frag;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return TITLES.length;
}
}
the above would give me a working ViewPager with 4 active tabs. Then I need to do all 4 individual Fragments. I'm giving out one example below.
public class FirstFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.firstfrag, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Button btn1 = (Button) getActivity().findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// what should I put in this block??????
Fragment fragment = new FirstFragSub1();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.pager, fragment); //<<------what should i replace???????
transaction.commitAllowingStateLoss();
}
});
}
}
The OnCreateView in FirstFragSub1 gets called but I don't see anything displayed on the screen. Basically just a blank. I know by replacing R.id.pager should not be the correct way, I'm just giving out an example of what I initial thought was.
Here is my FirstFragSub1
public class FirstFragSub1 extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i("FirstFragSub1","onCreateView is called");
return inflater.inflate(R.layout.subone, container, false);
}
}
Can someone please help me? I really out of idea...Thanks
there is a great tutorial and github here that covers this in detail.
http://tausiq.wordpress.com/2014/06/06/android-multiple-fragments-stack-in-each-viewpager-tab/
https://github.com/tausiq/ViewPagerMultipleFragmentDemo
this covers handling the backstack and multiple tabs with multiple views per tab. hope this help I was searching for a similar solution when i read your question.
Have FrameLayouts in the view that is being inflated by the Fragment. And onCreateView, replace the FrameLayout by the sub fragments that you want.
Also, be careful not to use the Activity's FragmentManager. getFragmentManager returns the Activity's FragmentManager and that will lead to an undesirable result (Only one fragment inside your ViewPager would have the sub fragments loaded). Use the getChildFragmentManager function instead.

Change Fragment with ViewPager

I am using PagerSlidingTab Library for ViewPager. And I want to change Fragment while scrolling of tabs. It is working fine. Check out my code.
I am using AsynTask() on each Fragment.
When the App opens with the MainActivity, First Fragment is attached to the activity, But It shows two AsynTask() dialog message, one from First and another from Second Fragment. And When I scroll to second tab, It shows dialog message of Third Fragment.
So, If I scroll from left to right in tabs, the Fragment right to the current fragment is displayed and if i scroll from right to left, the Fragment left to the current Fragment is displayed.
Please help me to solve the problem.
My Code:
public class PageSlidingTabStripFragment extends Fragment {
public static final String TAG = PageSlidingTabStripFragment.class
.getSimpleName();
public static PageSlidingTabStripFragment newInstance() {
return new PageSlidingTabStripFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.pager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view
.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "Instant Opportunity", "Events",
"Experts" };
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new InstantOpportunity();
case 1:
return new Events();
case 2:
return new Experts();
default:
break;
}
return null;
}
}
}
Explanation:
It turns out there is an easier implementation for scrollable tabs which doesn't involve another library. You can easily implement tabs into your app using normal Android code straight from the default SDK.
The Code
Main Class:
public class PageSlidingTabStripFragment extends Fragment {
//Variables
private ViewPager viewPager;
private PagerTitleStrip pagerTitleStrip;
public PageSlidingTabStripFragment() {
// Required empty public constructor
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Find your pager declared in XML
viewPager = (ViewPager) getView().findViewById(R.id.pager);
//Set the viewPager to a new adapter (see below)
viewPager.setAdapter(new MyAdapter(getFragmentManager()));
//If your doing scrollable tabs as opposed to fix tabs,
//you need to find a pagerTitleStrip that is declared in XML
//just like the pager
pagerTitleStrip = (PagerTitleStrip)
getView().findViewById(R.id.pager_title_strip);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.[your layout name here], container, false);
}
}
Adapter:
//Note: this can go below all of the previous code. Just make sure it's
//below the last curly bracket in your file!
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new InstantOpportunity();
}
if (arg0 == 1) {
fragment = new Events();
}
if (arg0 == 2) {
fragment = new Experts();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Instant Opportunity";
}
if (position == 1) {
return "Events";
}
if (position == 2) {
return "Experts";
}
return null;
}
}
Conclusion:
I hope this helps you understand another way to make scrollable tabs! I have examples on my Github Page about how to make each type (That being Fixed or Scrollable).
Links:
Fixed Tabs Example - Click Here
Scrollable Tabs Example - Click Here
Hope this helps!
Edit:
When asked what to import, make sure you select the V4 support fragments.
please use this example..its very easy.i already implement that.
reference link
hope its useful to you.its best example of pager-sliding-tabstrip.
Use
framelayout compulsory:
FrameLayout fl = new FrameLayout(getActivity());
fl.addView(urFragementView);
and then set your fragement view in this framelayout.

Android: "Navigation Type: Fixed Tabs + Swipe"

I'm trying to use Tabs + Swipe in an App and want to use the Navigation Type "Fixed Tabs + Swipe" which the ADT provides me when creating an Activity.
Sooo now the ADT spits out nice Code, which I slightly modified...
I completely understand the code and what's going on... But how can I teach the App to use my three Fragments instead of the stupid Dummy Frag? :(
I cannot find any tutorial which deals with the ADTs "Navigation Types"...
Thanks for your help!
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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 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);
}
});
//Adding Tabs
actionBar.addTab(actionBar.newTab().setText("Tab 1").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab 2").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab 3").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) {
}
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 DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
a switch-case to set the fragments is easy and makes it really clear. Let each of your fragment inflate the root view in your xml
#Override
public Fragment getItem(int index) {
Fragment fragment = null;
switch(index){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
break;
}
//set args if necessary (which it isn't?)
Bundle args = new Bundle();
args.putInt(ObjectFragment.ARG_OBJECT, index + 1);
fragment.setArguments(args);
//return fragment
return fragment;
}
But how can I teach the App to use my three Fragments instead of the stupid Dummy Frag?
You will notice that DummySectionFragment is referenced in getItem() of the SectionsPagerAdapter:
#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 DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
If you want to use different fragments, modify getItem() to return the fragment you want, given the supplied position (0-based page number).

Categories

Resources