there is a fragment in my activity in which there is a viewpager which has 5 fragments in it and inside the main activity i need to get one of the fragment from viewpager
Activity
public class MainActivity extends AppCompatActivity {
public void setFragment(){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mainFragment= new MainFragment();
FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, mainFragment,"mainFragment");
fragmentTransaction.commitAllowingStateLoss();
}
}, 250);
}
public void findFragment() {
mainFragment= (MainFragment) getSupportFragmentManager().findFragmentByTag("mainFragment");
viewPager = mainFragment.viewPager;
FragmentOne fragment = (FragmentOne) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + viewPager.getCurrentItem());
}
}
MainFragment
public class MainFragment extends Fragment{
private void initViewPagerAndTabs() {
viewPager = view.findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
pagerAdapter.addFragment(FragmentOne.newInstance(), "one");
pagerAdapter.addFragment(FragmentTwo.newInstance(), "two");
pagerAdapter.addFragment(FragmentThree.newInstance(), "three");
pagerAdapter.addFragment(FragmentFour.newInstance(), "four");
pagerAdapter.addFragment(FragmentFive.newInstance(), "five");
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
viewPager.setOffscreenPageLimit(3);
}
private static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
private PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
if i use "getFragmentManager()" instead of "getChildFragmentManager()" then it returns the fragment but when i use "getChildFragmentManager()" in viewPager it returns null in activity
Try this Running Code for 1 fragment, may it helps you in your code :
Main Activity
public class OpenQuran extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
TabLayout tabLayoutqaue;
Pager mAdapter;
MediaPlayer mp;
//This is our viewPagerss
ViewPager viewPager;
View mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_quran);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Read Quran");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Initializing the tablayout
tabLayoutqaue = (TabLayout) findViewById(R.id.tabLayoutqaue);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
mAdapter = new Pager(getSupportFragmentManager());
// 1 Fragment
mAdapter .addFrag(new Quran(), "Quran");
viewPager.setAdapter(mAdapter);
tabLayoutqaue.setupWithViewPager(viewPager);
tabLayoutqaue.setOnTabSelectedListener(this);
}
#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) {
}
Fargment Class :
public class parahlist extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.activity_parahlist, container, false);}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
View Pager Class:
public class Pager extends FragmentPagerAdapter {
//integer to count number of tabs
int tabCount;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
//Constructor to the class
public Pager(FragmentManager fm) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment Fragment, String title) {
mFragmentList.add(Fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Now This the code Of MainActivity, 2nd Fragment and 3rd one is View Pager class. You dont need to change or edit your View Pager Class. Just Create Java Class and Paste that code as it is.
In Main Activity the Line : mAdapter .addFrag(new Quran(), "Quran"); adding description and Fragment. You can add your own fragment after "new".
After that you have to put Tablayout widget in you Xml as Follows:
<android.support.design.widget.TabLayout
android:id="#+id/tabLayoutqaue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorgreen"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#color/colorback"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
And View Pager like:
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
/>
You may face some issue regarding tablayout :
Just put this line in your gradle build under dependecies:
compile 'com.android.support:design:25.3.1'
According to your version. for example you have 25.0.1
then line will be :
compile 'com.android.support:design:25.0.1
Still i m here to tell you more. if you got problem!
Related
I have an android app with TabLayout , I create TabItems and assign them to my TabLayout Dynamically with code in my MainActivity , in one of my Fragments, which is the Fragment for a TabItem , i have a button . what I want is when that button is clicked, its TabItem closes and destroys, how can I achieve that?
extra explanation: bellow is my MainActivity.java Code ( where most of my code for creating dynamic TabItems exists :
public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks {
public static List<Fragment> fragments = new ArrayList<>();
public static List<String> fragmentsTitle = new ArrayList<>();
ViewPager viewPager;
TabLayout tabLayout;
public List<Fragment> getFragments() {
return fragments;
}
public List<String> getFragmentsTitle() {
return fragmentsTitle;
}
public void addToFragments(Fragment fragment) {
fragments.add(fragment);
}
public void addToFragmentsTitle(String title) {
fragmentsTitle.add(title);
}
public Fragment getFragmentsWithPosition(int position) {
return fragments.get(position);
}
public String getFragmentsTitleWithPosition(int position) {
return fragmentsTitle.get(position);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_drawer);
this.tabLayout = findViewById(R.id.tab_layout);
this.viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
SetUpViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public void SetUpViewPager(ViewPager viewPager) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter((getSupportFragmentManager()));
Adapter.AddFragmentPage(new SignInFragment(),"ورود");
Adapter.AddFragmentPage(new ContactsFragment(),"ارتباطات");
Adapter.AddFragmentPage(new RegisterFragment(),"ثبت نام");
viewPager.setAdapter(Adapter);
}
#Override
public void send_user_object() {
/* this is the implementation of abstract function defined
in one of my tab , in which it has a button and when
button is clicked i want the tab to be removed . */
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void AddFragmentPage(Fragment frag,String title) {
MainActivity.this.addToFragments(frag);
MainActivity.this.addToFragmentsTitle(title);
}
public Fragment getItem(int position) {
return MainActivity.this.getFragmentsWithPosition(position);
}
public CharSequence getPageTitle(int position) {
return MainActivity.this.getFragmentsTitleWithPosition(position);
}
public int getCount() {
List<Fragment> frag = MainActivity.this.getFragments();
return frag.size();
}
}
}
in one of my predefined tabs , i have a listview , when user clickes on an item on the list view , the detail of the item opens in a new tab , then user can see the detail by clicking on that tab . what i want is how user can close ( destroy ) that detail tab about one of items ? ( remember it is creating dynamically )
how can I remove ( close ) the TabItem with Click of a Button in that TabItem Fragment?
Plase help me , thank you beforehand .
It's not a good practice to change horizontal navigation by adding another fragment. If it's not absolutely required by your customer, create a new fragment and just replace the current one like this:
Fragment detailsFragment=new ContactsFragment()
getSupportFragmentManager.beginTransaction()
.addToBackStack("tag")
.replace(R.id.containerName, detailsFragment, "another_tag")
.commit()
At your detailsFragment your close button's clickListener just call getActivity.getSupportFragmentManager.popBackStack()
and it restores previous state.
Hope I could help you.
I solved my problem by :
first ) creating an interface in the UserDetailFragment, which you all know for communication with MainActivity, I had to do that.
but for what did I need communicating with the MainActivity ?
Answer : as you see in my code , my FragmentPagerAdapter class is defined there , and i needed my public List<Fragment> fragments = new ArrayList<>(); and public static List<String> fragmentsTitle = new ArrayList<>(); that i had saved my fragments into them , and also mytabLayout.
Seconde ) i had to define tabLayout.addOnTabSelectedListener(){} with its method OnTabSelected() , i needed that because i get the current index of the tab using addOnTabSelectedListener(){} .
Third ) i defined removeTabPage(int position) in the FragmentPagerAdapter .
Forth ) i created a method as bellow ( which is the implementation of the abstract method of UserDetailFragment interface.
#Override
public void close_tabitem() {
tabLayout.removeTabAt(tabposition_number);
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.removeTabPage(tabposition_number);
Adapter.notifyDataSetChanged();
}
and here is my whole code for: MainActivity.Java
public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks, UserDetailFragment.DetailCallBacks {
android.support.v7.widget.Toolbar toolbar;
public static List<Fragment> fragments = new ArrayList<>();
public static List<String> fragmentsTitle = new ArrayList<>();
ViewPager viewPager;
TabLayout tabLayout;
int tabposition_number;
public List<Fragment> getFragments() {
return fragments;
}
public List<String> getFragmentsTitle() {
return fragmentsTitle;
}
public void addToFragments(Fragment fragment) {
fragments.add(fragment);
}
public void addToFragmentsTitle(String title) {
fragmentsTitle.add(title);
}
public Fragment getFragmentsWithPosition(int position) {
return fragments.get(position);
}
public String getFragmentsTitleWithPosition(int position) {
return fragmentsTitle.get(position);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_drawer);
this.tabLayout = findViewById(R.id.tab_layout);
this.viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
SetUpViewPager(viewPager);
this.toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = findViewById(R.id.navigation_view);
navigationView.setItemIconTintList(null);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabposition_number = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public void SetUpViewPager(ViewPager viewPager) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter((getSupportFragmentManager()));
Adapter.AddFragmentPage(new SignInFragment(),"ورود");
Adapter.AddFragmentPage(new ContactsFragment(),"ارتباطات");
Adapter.AddFragmentPage(new RegisterFragment(),"ثبت نام");
viewPager.setAdapter(Adapter);
}
#Override
public void send_user_object(UserObject userObject) {
// tabLayout.removeTabAt(tabposition_number);
// myViewPagerAdapter.remove
}
#Override
public void create_user_detail_tab(UserObject userObject) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
UserDetailFragment userDetailFragment = new UserDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("name",userObject.getName());
bundle.putString("family",userObject.getFamily());
bundle.putString("email",userObject.getEmail());
userDetailFragment.setArguments(bundle);
Adapter.AddFragmentPage(userDetailFragment,userObject.getName());
viewPager.setAdapter(Adapter);
}
#Override
public void close_tabitem() {
tabLayout.removeTabAt(tabposition_number);
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.removeTabPage(tabposition_number);
Adapter.notifyDataSetChanged();
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void removeTabPage(int position) {
fragments.remove(position);
fragmentsTitle.remove(position);
notifyDataSetChanged();
}
public void AddFragmentPage(Fragment frag,String title) {
MainActivity.this.addToFragments(frag);
MainActivity.this.addToFragmentsTitle(title);
}
public Fragment getItem(int position) {
return MainActivity.this.getFragmentsWithPosition(position);
}
public CharSequence getPageTitle(int position) {
return MainActivity.this.getFragmentsTitleWithPosition(position);
}
public int getCount() {
List<Fragment> frag = MainActivity.this.getFragments();
return frag.size();
}
}
}
and here is the UserDetailFragment.Java , which acts as my TabItem :
public class UserDetailFragment extends Fragment {
View view;
DetailCallBacks detailCallBacks;
public UserDetailFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.user_detail_fragment,null);
return view;
}
#Override
public void onResume() {
super.onResume();
Button closebtn = view.findViewById(R.id.detail_close_button);
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detailCallBacks.close_tabitem();
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
detailCallBacks = (DetailCallBacks)context;
}
public interface DetailCallBacks {
public void close_tabitem();
}
}
Hope It Helps You.
But do remember, you can not use this button. put the button in some other tabitem or in the menu.
or you can use :
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
to change the tabitem and then fire the event .
enjoy .....
Actually, i am implementing a TabLayout, so in main MainActivity, I load the TabFragment and in the tabFragment(contain two fragments) I used the ViewPager.
So the problem is when I am on fragment two in TabLayout and the after the screen goes off it will move to the Fragment one(Default one). So how can I tackle this one
Here is TabFragment Code:
public class TabFragment extends Fragment {
public TabFragment() {
// Required empty public constructor
}
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View x=inflater.inflate(R.layout.content_main_menu,null);
tabLayout=(TabLayout) x.findViewById(R.id.tabs);
viewPager =(ViewPager) x.findViewById(R.id.viewpager);
setupViewPager(viewPager);
//viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOffscreenPageLimit(1);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
private void setupViewPager(ViewPager viewPager) {
MyAdapter adapter = new MyAdapter(getChildFragmentManager());
adapter.addFragment(new HomeFragment(), "Fragment One");
adapter.addFragment(new Offers(), "fragment Two");
viewPager.setAdapter(adapter);
}
class MyAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Use FragmentStatePagerAdapter instead of FragmentPagerAdapter. read documentation here. FragmentStatePagerAdapter only stores the savedInstanceState of fragments, and destroys all the fragments when they lose focus.
I am trying to replace one of the fragments inside the ViewPager with another one.
The pager is composed by two pages: Fragment1 , Fragment2
inside the fragment2, there is a button. When I click on the button, it will replace the current fragment, Fragment2, with Fragment3. For Fragment2, I want it to be destroyed and not exist anymore.
The implementation Code:
Layout for activity_main:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
main_activity :
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mSectionsPageAdapter.clearAll();
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "Tab 1");
adapter.addFragment(new Tab2Fragment(), "Tab 2");
adapter.notifyDataSetChanged()
viewPager.setAdapter(adapter);
}
The Adapter:
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
Fragment2:
public class Tab2Fragment extends Fragment {
private static final String TAG = "Tab2Fragment";
private Button btnTEST;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2_fragment,container,false);
btnTEST = (Button) view.findViewById(R.id.btnTEST2);
btnTEST.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 2", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
Update :
I tried to implement the method clearAll in the adapter put I noticed the mFragmentList.size() return 0 why ?
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
Log.d("tmz",mFragmentList.size()+" From addFragment"); // return 1 & 2
}
#Override
public int getCount() {
return mFragmentList.size();
Log.d("tmz",mFragmentList.size()+"getCount "); // return 2
}
public void clearAll(){
Log.d("tmz",mFragmentList.size()+" From addFragment"); // return 0 why ?
for(int i=0; i<mFragmentList.size(); i++)
fragMan.beginTransaction().remove(mFragmentList.get(i)).commit();
mFragmentList.clear();
mFragmentList=new ArrayList<Fragment>();
notifyDataSetChanged();
}
remove from mFragmentList (and mFragmentTitleList) and add new, then call notifyDataSetChanged? also add to your SectionsPageAdapter for force redrawing ViewPager when notified.
public int getItemPosition(Object object) {
return POSITION_NONE;
}
not most efficient, but sufficient for your purposes. for adapter:
public void removeLastFragment() {
if(mFragmentList.size()==0)
return;
mFragmentList.remove(mFragmentList.size()-1);
mFragmentTitleList.remove(mFragmentTitleList.size()-1);
}
For zero it was because
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
was repeated twice, and I solve my issue with use replace fragment inside the tab
I am trying to replace the fragment views in my tabbed swipe view with another fragment but it does not replace or add the fragment, instead it only adds the menu of the fragment in all the tabbed activity.
I want when in a particular tab activity in my swipeview, I can replace the content(fragmentA) with another fragment(FragmentBoy) which can override that particular menu of that particular tabbed activity. Also could also work when replacing content(fragmentB) with another fragment(FragmentGirl).
Please I stucked, I need a help on this-
public class Main2Activity extends AppCompatActivity {
private ViewPager mViewPager;
private int[] tabIcons = {
R.drawable.ic_grand,
R.drawable.ic_event,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
setupTabIcons();
}
private void setupTabIcons() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
}
private void setupViewPager(ViewPager mViewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentA(), "ONE");
adapter.addFrag(new FragmentB(), "TWO");
mViewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return null;
}
}
public static class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.grand,container,false);
Button tb=(Button)view.findViewById(R.id.btn_c);
tb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction().add(R.id.swapfrag, new BOYFragment());
transaction.commit();
}
});
return view;
}
}
Hi I have a TabLayout and ViewPager inside a fragment. But I can not slide beetween tab to come to child fragment (Working normally when in Activity but not work in fragment).
Here is my code for Tablayout inside fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflateView = inflater.inflate(R.layout.fragment_assign_beacon_to_event, container, false);
//Viewpager and TabLayout
viewPager = (ViewPager)inflateView.findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
tabLayout = (TabLayout)inflateView.findViewById(R.id.tabLayout);
// Inflate the layout for this fragment
return inflateView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
Any here is my Custom Adapter class
private class CustomAdapter extends FragmentPagerAdapter {
private String fragments[] = {"Assign Event", "Manage Event"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// return new AssignEventToBeacon();
return new Test1();
case 1:
return new ManageEventAssigned();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
I doubt i have problem with this line:
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
Anyhelp is much appreciate, thanks
I have done a similar project and here is my code for the fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.outer_fragment, container, false);
setHasOptionsMenu(true);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
Log.v("Layout","Tabs");
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
tabLayout.setTabTextColors(Color.parseColor("#707070"), Color.parseColor("#FFFFFF"));
assert viewPager != null;
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new Tab1Fragment(), "PHOTOS");
adapter.addFragment(new Tab2Fragment(), "HI-FIVES");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
You need to use getChildFragmentManager() in Fragment instead of getFragmentManager().
From getChildFragmentManager() documentation
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.
From getFragmentManager() documentation
Return the FragmentManager for interacting with fragments associated
with this fragment's activity.
In simple words,
Use getChildFragmentManager() for Child Fragments
Use getFragmentManager() for Fragments inside Activity
One can see #this answer for complete code.