I've a FrameLayout and Navigation Drawer in Main Activity. I'm transacting a fragment in Main Activity using this FrameLayout. In this fragment, I've TabLayout and ViewPager. Now what I want is to open a new fragment on Button click in the ViewPager fragment. But app crashes on Button click. Is it becuz FrameLayout is in Main Activity and the Button is in child fragment's child fragment? I've tried using FrameLayout in Tabs but that would mean I would have to use FrameLayouts for each Tab and I don't want that. So any help in this regard will be much appreciated. Also, how to handle back arrow click in toolbar to go back to previous fragment?
public class HomeFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.homefragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new TabOne();
case 1 : return new TabTwo();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "ONE";
case 1 :
return "TWO";
}
return null;
}
}
}
public class TabOne extends Fragment {
private Button newFrag;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.tabone, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
newFrag = (Button)view.findViewById(R.id.button);
newFrag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction xfragmentTransaction = getChildFragmentManager().beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewFrag()).addToBackStack(null).commit();
}
});
}
}
public class MainActivity extends AppCompatActivity {
DrawerLayout myDrawerLayout;
NavigationView myNavigationView;
Toolbar toolbar;
ActionBarDrawerToggle mDrawerToggle;
FragmentManager myFragmentManager;
FragmentTransaction myFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
myNavigationView = (NavigationView) findViewById(R.id.nav_drawer) ;
myFragmentManager = getSupportFragmentManager();
myFragmentTransaction = myFragmentManager.beginTransaction();
myFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
myNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem selectedMenuItem) {
myDrawerLayout.closeDrawers();
if (selectedMenuItem.getItemId() == R.id.nav_profile) {
FragmentTransaction fragmentTransaction = myFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new ProfileFragment()).addToBackStack(null).commit();
}
if (selectedMenuItem.getItemId() == R.id.nav_history) {
FragmentTransaction xfragmentTransaction = myFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new HistoryFragment()).addToBackStack(null).commit();
}
return false;
}
});
toolbar = (Toolbar)findViewById(R.id.toolbar);
mDrawerToggle = new ActionBarDrawerToggle(this, myDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
myDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
FATAL EXCEPTION: main
Process: com.sam.demonavigation, PID: 8523
java.lang.IllegalArgumentException: No view found for id 0x7f0c006b (com.sam.demonavigation:id/containerView) for fragment HistoryFragment{42016928 #0 id=0x7f0c006b}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1059)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)
This link proved to be very useful. Using the method mentioned in my link I was able to use the FrameLayout in my Main Activity to open any fragment
// This is the button click event in one of the TabLayout fragment
newFrag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment var1 = new NewFrag();
((MainActivity)getActivity()).replaceFragment(var1);
}
});
// Add this method in MainActivity
public void replaceFragment(Fragment fragment){
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.containerView, fragment).addToBackStack(null);
t.commit();
}
.
1-Create ViewPager object
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
2-then add Custom FragmentPagerAdapter
ViewPagerAdapter adapter = new ViewPagerAdapter(this);
adapter.addFrag(new Fragment1(), "Item1");
adapter.addFrag(new Fragment2(), "Item2");
adapter.addFrag(new Fragment3(), "Item3");
viewPager.setAdapter(adapter);
3-After that write custom adapter definition
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 mFragmentTitleList.get(position);
}
Related
I have Navigation drawer.and in First fragmant of Navigation drawer there is viewpager and there is information coming from network.Viewpager has 2 fragments also.When I switch fragment to Settings fragment of navigation drawer and coming back to this fragment everything is gone..There is no any information..How can i save state of this fragment?Or in which method can i send request to take information from network again
MainActivity
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.motherFragments, FragmentMainPage.newInstance("MainPage"))
.commit();
}
#Override
public void onBackPressed() {
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
drawer.openDrawer(GravityCompat.START);
break;
}
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
if (item.isChecked()) {
drawer.closeDrawer(GravityCompat.START);
return false;
}
switch (item.getItemId()) {
case R.id.home: {
fragment = new FragmentMainPage().newInstance("Sample");
break;
}
case R.id.settings:{
Intent intent = new Intent(this,SettingsActivity.class);
startActivity(intent);
break;
}
case R.id.incoming:{
fragment = new FragmentIncomingPage().newInstance("Sample");
break;
}
}
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction().replace(R.id.motherFragments, fragment)
.commit();
item.setChecked(true);
}
drawer.closeDrawer(GravityCompat.START);
return true;
} }
Fragment1 of Navigation drawer
public class FragmentMainPage extends Fragment implements
ViewPager.OnPageChangeListener {
private Toolbar toolbar;
private MainActivity activity;
private TabLayout tabLayout;
private ViewPager viewPager;
String[] names = {
"Sample 1",
"Sample 2"
};
private static FragmentMainPage myInstance;
public static FragmentMainPage newInstance(String testString){
Bundle bundle = new Bundle();
bundle.putString("test",testString);
if(myInstance == null){
myInstance = new FragmentMainPage();
}
myInstance.setArguments(bundle);
return myInstance;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = ((MainActivity) context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_fragment_main,container,false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
activity.setTitle(getResources().getText(R.string.bosh_sahifa));
activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewpager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(this);
setupTabName();
return view;
}
private void setupViewpager(ViewPager viewPager) {
MyAdapter adapter = new MyAdapter(getActivity().getSupportFragmentManager());
adapter.addFragement(new Fragment_home1());
adapter.addFragement(new Fragment_home2());
viewPager.setAdapter(adapter);
}
private void setupTabName() {
tabLayout.getTabAt(0).setText(names[0]);
tabLayout.getTabAt(1).setText(names[1]);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
private class MyAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = 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 addFragement(Fragment fragment){
mFragmentList.add(fragment);
}
}
}
Fragment 2 of Navigation drawer
public class FragmentIncomingPage extends Fragment {
private Toolbar toolbar;
private MainActivity activity;
private static FragmentIncomingPage myInstance;
public static FragmentIncomingPage newInstance(String testString){
Bundle bundle = new Bundle();
bundle.putString("test",testString);
if(myInstance == null){
myInstance = new FragmentIncomingPage();
}
myInstance.setArguments(bundle);
return myInstance;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = ((MainActivity) context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_fragment_incoming,container,false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
activity.setTitle(getResources().getText(R.string.Incoming));
activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return view;
}
}
Have 3 fragments and swipe to 3rd fragment then back to 1st fragment, the 1st fragment's data is gone?
You can use fragment.addToBackStack(null) method.
like,
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, A);
ft.addToBackStack(null);
ft.commit();
There is few ways to achieve it.
You can use SharedPreferences to save current Fragment by mViewPager.getCurrentItem() and set it again once you come to the ViewPager activity by navigation drawer button.
Use BaseFragment and implement your fragments from the Base Fragment, keep current visible fragment of the view pager in side the Base Fragment as protected variable.
As Base Fragment which is describe above, You can use Bas Activity class.
I have 2 Tabs as fragments in a ViewPager in an Activity
When I tap the second tab in the layout, the OnTabUnselected method works.
However, when I slide the screen from one tab to another, the method isn't called.
How do I achieve this calling of method by both means "Tapping as well as in a Sliding Gesture"
My Activity class is:
public class OrderActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FloatingActionButton printAction;
ViewPagerAdapter adapter;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_text_tabs);
TypefaceUtil.overrideFont(getApplicationContext(), "serif", "fonts/opensans.tff");
//TypefaceUtil.overrideFont(getApplicationContext(), "arial", "fonts/opensans.tff");
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
//setupTabIcons();
printAction = (FloatingActionButton) findViewById(R.id.float_print);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabSelected",Toast.LENGTH_LONG).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
String ac = null;
int pos = viewPager.getCurrentItem();
Fragment activeFragment = adapter.getItem(pos);
if(pos==0){
ac= ((PersonalDetailFragment)activeFragment).getXmlValue();
}
Toast.makeText(getApplicationContext(),ac,Toast.LENGTH_LONG).show();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabReselected",Toast.LENGTH_LONG).show();
}
});
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new PersonalDetailFragment(), "Personal");
adapter.addFrag(new OrderItemsFragment(), "Invoice");
viewPager.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 mFragmentTitleList.get(position);
}
}
}
Fragment A:
public class FragmentA extends Fragment {
private EditText custName;
public PersonalDetailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
custName = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
public String getXmlValue(){
return custName.getText().toString();
}
}
Fragment B:
public class FragmentB extends Fragment {
private EditText contactNo;
public PersonalDetailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
contactNo = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
}
You can use the ViewPager.addOnPageChangeListener() method to register a listener and get notified about changing the current tab with a pager swipe.
There is a really nice tutorial here.
In your fragment you can use a method named setVisibilityHint that is called every time the visibility of the fragment has been changed. There is a boolean parameter that can be true or false depending if the fragment is visible or not
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
I am creating ListView in my app in tab Activity.but when app runs emulator shows blank activity. I don't know what is the issue with this. Please help. I am not getting list in the tab. I am getting list in simple activity without tab but I can't see list in tab activity. Let me know if you want other information.
This my ArtistTab.java activity
public class ArtistsTab extends Fragment {
ListView listView1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.artist, container, false);
listView1 =(ListView)v.findViewById(R.id.listView);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// add your code here which executes after the execution of onCreateView() method.
ArrayList<String>my=new ArrayList<>();
my.add("devesh");
my.add("devesh");
my.add("devesh");
my.add("devesh");
ArrayAdapter arrayAdapter=new ArrayAdapter(getActivity(), layout.simple_list_item_1,my);
listView1.setAdapter(arrayAdapter);
}
}
This is my main Activity
public class MainActivity extends AppCompatActivity {
public ViewPagerAdapter pagerAdapter;
private ViewPager mViewPager;
private Toolbar toolbar;
private TabLayout tabLayout;
public static View rootView;
public static int tabNo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setAdapter(pagerAdapter);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
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;
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1: {
rootView = inflater.inflate(R.layout.songs, container, false);
break;
}
case 2: {
rootView = inflater.inflate(R.layout.album, container, false);
break;
}
case 3: {
rootView = inflater.inflate(R.layout.genres, container, false);
break;
}
case 4: {
rootView = inflater.inflate(R.layout.artist, container, false);
break;
}
}
return rootView;
}
}
}
artistTab xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</RelativeLayout>
Try like this to tabs with viewpager
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ArtistsTab(), "ArtistsTab");
adapter.addFragment(new SongsTab(), "Songs");
//Do your stuff here
viewPager.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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
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.