Just need a workaround!
I had already implemented drawer, now need to place sliding tabs in one of those fragments.
Fragment Class:
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
Method i am using needs to extend the same ‘FragmentTwo’ class to ‘ActionBarActivity’. Here is the code:
public class FragmentTwo extends ActionBarActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {“Test1”, “Test2”, “Test3”};
int Numboftabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
I know a class cannot be extended to more than one class in java. But is there some other way to get this done?
Placing a ViewPager inside a Fragment that is created by a NavigationDrawer is the same way as placing a ViewPager inside a simple Fragment created inside an Activity.
Inside of class Fragment two implement the ViewPager like that:
public class FragmentTwo extends Fragment {
private ViewPager pager;
private ViewPagerAdapter adapter;
private SlidingTabLayout tabs;
private static CharSequence titles[];
private final int numOfTabs = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_slidetab, container, false);
// set your titles here
adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager(),titles, numOfTabs);
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
//mSwipeRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swipeRefreshLayout);
return rootView;
}
}
For the ViewPager you need an Adapter class:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if(position == 0)
{
FragmentForDay tab1 = FragmentSlide.newInstance(0);
return tab1;
}
else if(position == 1)
{
FragmentSlide tab2 = FragmentSlide.newInstance(1);
return tab2;
}
else
{
FragmentSlide tab3 = FragmentSlide.newInstance(2);
return tab3;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
And each of your slide tabs, called FragmentSlide here, can be inflated as a normal Fragment:
public class FragmentSlide extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_Slide, container, false);
// Inflate the layout for this fragment
return rootView;
}
public static FragmentSlide newInstance(int selectedIdForIndex) {
FragmentSlide fragment = new FragmentSlide();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_ID, selectedIdForIndex);
fragment.setArguments(args);
return fragment;
}
}
Related
This question already has an answer here:
Android Viewpager inside of Viewpager not showing layout
(1 answer)
Closed last month.
I have a BottomNavigation bar in main activity. Which has 5 items.
Here is the getitem method for that bottomnavigation
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new ChatRoomPage();
case 1:
return new TopicPage();
case 2:
return new TopicPage();
case 3:
return new Leaderboard();
case 4:
return new Stats();
}
return new ChatRoomPage();
}
I have added TopicPage() for testing.
So topic page is a fragment with tab layout. And that fragment shows three other fragments using tab view.
TopicPage() in case 2 is working fine.
But in case 3 fragment TopicPage() is showing. It's also calling the three fragments in tab layout (Getting message in log). But not visible in ViewPager. And the underline on tablayout is not sliding from one tab to another tab with animaton. I have to slide it manually.
And,
When I add a single fragment like Stats() or Leaderboard() it works.
Screenshot
Topic Page onCreateview
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
v = inflater.inflate(R.layout.topic_page, container, false);
tabLayout = v.findViewById(R.id.tab);
pager = v.findViewById(R.id.pager);
pager.setOffscreenPageLimit(4);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
pager.setAdapter(new TopicPagerAdapter(getFragmentManager()));
tabLayout.setupWithViewPager(pager);
return v;
}
So I don't know why I am getting this problem...
Need Help :(
Override a method in TopicPage() fragment called setUserVisibilityHint()
and in that method after the return statement ...write
if(getActivity()!=null) { viewPager.setAdapter(....youradapter); } I think it will work. First initialize the adapter of viewPager then set the adapter.....Let me know if it works..
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
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("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
PagerAdapter For Fragment
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
FirstFragment
public class TabFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
}
I am beginning with Android and I have a NavigationView along with Tabular layout. I want to change the values in the tabs fragments based on the selection made in the navigation view. Here is my code-
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Context mainActivityContext;
Intent serviceIntent;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
private SectionsPagerAdapter mSectionsPagerAdapter;
private String valSelected = "";
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editor = sharedPref.edit();
mainActivityContext = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.sel1) {
valSelected = "First";
NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
findFragmentById(R.id.title_notification);
fragment_obj.updateView();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
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_main2, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText("HELLO");
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return new NotificationFragment();
}
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab1";
case 1:
return "Tab2";
case 2:
return "Tab3";
case 3:
return "Tab4";
}
return null;
}
#Override
public int getItemPosition(Object object) {
if (object instanceof NotificationFragment) {
((NotificationFragment)object).updateView();
}
return super.getItemPosition(object);
}
}
}
This is my NotificationFragment
NotificationFragment.java
public class NotificationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.notification_layout, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.title_notification);
textView.setText(MainActivity.coinSelected.toUpperCase());
return rootView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void updateView(){
TextView text = (TextView) this.getView().findViewById(R.id.title_notification);
text.setText(MainActivity.valSelected);
}
}
But when I try to update the value in my MainActivity using
NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
findFragmentById(R.id.title_notification);
it gives me null.
Edit
Here is the notification layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/title_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BTC/USD"
android:textSize="26dp"/>
</LinearLayout>
I faced this problem once when in my MainActivity.java i was importing android.support.v4.app.Fragment; and in my other class i was importing android.app.Fragment. I changed it to the same thing and findFragmentById(R.id) now returned the right fragment.
in your code
NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
findFragmentById(R.id.title_notification);
R.id.title_notification must be the id of fragment,but in your xml,it's a textview
I've created a tab view by Android Studio, this is the default code for MainActivity.java:
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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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.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_main, 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) {
// 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);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
so I have three xmls:
one.xml
two.xml
fragment_main.xml
I want to change the layout of each tab to an unique xml that I mentioned.
I tried this way:
Added this to my MainActivity.java:
public class FrChange extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.one, container, false);
return rootView;
}
}
and then I changed this:
View rootView = inflater.inflate(R.layout.fragment_main, 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;
to this:
return new FrChange();
But it throws me bunch of errors.
What should I do?
My problem was with the adapter.
Check out link for further information : different layout for each tab
I have a tabbed activity with 1 fragment, this fragment has a button, i want when i click the button it create a new fragment and i can swipe between the two fragments
this is the main activity
public class ActivityBeamRec extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public static CustomViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_beam_rec);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (CustomViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPagingEnabled(false);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 : return PlaceholderFragment.newInstance(position + 1);
// case 1 : return the new fragment ;
}
return null;
}
#Override
public int getCount() {
return 1 ;
}
}
}
this is the fragment i have.
public 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) {
final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);
final EditText etxb;
etxb = (EditText)rootView.findViewById(R.id.editText);
final Button buDesign = (Button)rootView.findViewById(R.id.buDesign);
buDesign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double b;
b = Double.valueOf(etxb.getText().toString());
\\here i want the button to create the second fragment and pass the variable d to it
ActivityBeamRec.mViewPager.setPagingEnabled(true); // this is to enable the siwpe between the fragments
ActivityBeamRec.mViewPager.setCurrentItem(2); // ths is to set the new fragment as the current view
}
});
return rootView;
}
}
the second fragment should go through on create view stage after the button is pressed, and please tell where i put each code if there is a way to do this.
ActivityBeamRec:
public class ActivityBeamRec extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
// This list holds the fragments for the pages displayed by view pager.
private List < Fragment > fragments = new ArrayList < Fragment > ();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
// Add the first fragment:
fragments.add(PlaceholderFragment.newInstance(1));
}
private void addFragment(Fragment fragment) {
fragments.add(fragment);
// Notify view pager that the contents of the adapter has changed and that it needs to update
// its pages:
notifyDataSetChanged();
// Since content of view pager has changed, re-wire tab layout:
tabLayout.setupWithViewPager(mViewPager);
// Set the current page in the view pager to the last added fragment:
mViewPager.setCurrentItem(fragments.size() - 1);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
// Set the tab title as the number of the current section:
return "SECTION " + (position + 1);
}
}
/**
* Adds a new fragment (page) to the view pager.
* This method can either be public or package-private (without any modifier) depending on the package
* of 'PlaceholderFragment'. Since you're new to Java please refer the link to access modifiers below.
*
* #param fragment the fragment to be added to the view pager
**/
public void addFragment(Fragment fragment) {
mSectionsPagerAdapter.addFragment(fragment);
}
/**
* Returns the number of the next section (page) to be added.
*
* #return the next section number
*/
public int getNextSectionNumber() {
return mSectionsPagerAdapter.getCount() + 1;
}
}
PlaceholderFragment:
public 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) {
final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);
final EditText etxb;
etxb = (EditText) rootView.findViewById(R.id.editText);
final Button buDesign = (Button) rootView.findViewById(R.id.buDesign);
buDesign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double b;
b = Double.valueOf(etxb.getText().toString());
//here i want the button to create the second fragment and pass the variable d to it
int nextSectionNumber = ((ActivityBeamRec) getActivity()).getNextSectionNumber();
((ActivityBeamRec) getActivity()).addFragment(PlaceholderFragment.newInstance(nextSectionNumber));
}
});
return rootView;
}
}
When the button in the fragment is clicked the following things occur in sequence:
addFragment() method of parent activity is called by passing the fragment instance to be added. This public method is used to access the private member mSectionsPagerAdapter of parent activity. We can do away with this method if mSectionsPagerAdapter is made public or package-private.
SectionsPagerAdapter adds the passed-in fragment to its list of fragments and then notifies the view pager that its data set has changed.
TabLayout is refreshed to accommodate the new fragment (page).
Finally the view pager is made to scroll to the added fragment using the setCurrentItem() method.
Reference:
Java Access Control Modifiers
List Data Structure in Java
In your SectionsPagerAdapter
private ArrayList<Fragment> fragments = new ArrayList<>();
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
if(position<fragments.size())
return fragments.get(position);
throw new NullPointerException("No Fragment with this position found.");
}
public void addFragment(Fragment newFragment){
fragments.add(newFragment);
}
In the MainActivity before setting the adapter with mViewPager.setAdapter(mSectionsPagerAdapter); add your first fragment(the PlaceHolder in your case). (or do it in the SectionPagerAdapter's constructor).
And then in your OnClickListener call the SectionPagerAdapter's addFragment method.
EDIT: In MainActivity:
mSectionsPagerAdapter.addFragment(PlaceholderFragment.newInstance(0));
mSectionsPagerAdapter.setAdapter(mSectionsPagerAdapter);
I have implemented THIS in my activity and it works perfectly fine, but I would like to change the content of my fragment every time when the user slides a finger on the screen. Now it shows the same text not considering the slide(left to right or right to left). How can I handle it? I know that I'm missing an extremely small part here, but I'm not able to understand what is going on. Where should I add the listener and handle the actions?
Here is what I have so far:
public class ViewrerAct extends FragmentActivity {
private static final int NUM_PAGES = 5;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bulgarian_sayings, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_viewer, container, false);
return rootView;
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
System.out.println("inside!");
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
AND
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_viewer, container, false);
return rootView;
}
}
You should post the code for ScreenSlidPagerAdapter.
Nevertheless, you need to override setPrimaryItem method of pager adapter that gets called every time you slid the pager and change the displayed page.
for ex:
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
currentPage = position;
}
You can store your Strings in array and pass it to adapter and inside adapter you can change the content of the fragment with respect to the selected position.
Post pager adapter as well if want more appropriate example.
In your case, you can simply pass string array, assuming you just want different test to be displayed, to adapter for ex:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
String[] displayText;
public ScreenSlidePagerAdapter(FragmentManager fm,String[] displayText) {
super(fm);
this.displayText=displayText;
}
#Override
public Fragment getItem(int position) {
System.out.println("inside!");
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
fragment.setText(displayTest[position]);
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
And your Fragment class would change to:
public class ScreenSlidePageFragment extends Fragment {
private String text;
public void setText(String text){
this.text=text;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_viewer, container, false);
((TextView)rootView.findViewById(textViewId)).setText(Text);
return rootView;
}
}