how to replace fragments on tab? - android

I have an activity with 2 tabs. What im trying to do is to replace between 2 fragments when each tab is pressesd. I also have 2 fragments: fragmentOne and fragmentTwo.When tab one is pressed i want to show fragmentOne and when tab two is pressed i want to show fragmentTwo.
I'm not sure if i should create a container layout in the activity and there add the fragmentOne and fragmentTwo, or maybe there is another other way to do it?
here is my code
public class InboxActivity extends AppCompatActivity {
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Fragment fragment;
int position = tab.getPosition();
//requests = position - 0
//invitations = position - 1
switch (position){
case 0:
break;
case 1:
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
when case is 0 i want to show fragmentOne
when case i 1 i want to show fragmentTwo
How should i do that?

You can do it as follow:
public void onTabSelected(TabLayout.Tab tab) {
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
Here is a tutorial for more information

Use a ViewPager instead.
Set an adapter in the view pager and use it with a TabLayout using
tabLayout.setupWithViewPager(viewPager);

Related

how can i solve android tab layout switching

i am developing an android app which has four fragments with tablayout and each fragment has connection error dialog box.
first problem is,when i start my app,four fragments work
simultaneously at the same time.So,when i occur connection error four
dialog boxes are shown in first fragment When i switch to second tab
it doesn't show his dialog box because his dialog is shown in first
fragment.
second problem is,i create that fragments with swipe refresh layout
to fetch data from server.I call onRefresh method in onCreate method.
when i start my app,first fragment data is loaded from server but
when i switch first tab to second tab,it is not loaded his data from
server but when i switch first tab to third tab,it is work.
Also,when i switch second tab to third tab,it is not loaded data from
server but when i switch second tab to fourth tab,it is work. It is
only work when i switch tabs with one tab differ. Is there anyway to
solve that problems.
I searched this problems from internet but i didn't get my problems answer.
Please anyone help me.Thanks in advance.....
Sorry for my poor english
this is tablyout code
viewPager = (ViewPager) findViewById(R.id.viewpagerMain);
tabLayout = (TabLayout) findViewById(R.id.tablayoutMain);
tabLayout.addTab(tabLayout.newTab().setText("Noticeboard"));
tabLayout.addTab(tabLayout.newTab().setText("News"));
tabLayout.addTab(tabLayout.newTab().setText("Events"));
tabLayout.addTab(tabLayout.newTab().setText("Result"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(0);
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) {
}
});
This is MyAdapter class
class MyAdapter extends FragmentStatePagerAdapter {
int num_of_tab;
public MyAdapter(FragmentManager fm, int num_of_tab) {
super(fm);
this.num_of_tab = num_of_tab;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
NoticeBoardFragment noticeBoardFragment = new NoticeBoardFragment();
return noticeBoardFragment;
case 1:
NewsFragment newsFragment = new NewsFragment();
return newsFragment;
case 2:
EventsFragment eventsFragment = new EventsFragment();
return eventsFragment;
case 3:
ResultFragment resultFragment = new ResultFragment();
return resultFragment;
default:
return null;
}
}
#Override
public int getCount() {
return num_of_tab;
}
}
Override setUserVisibleHint in each fragment and write your dialog box code in if(isVisibleToUser) instead of Oncreate. This should solve your problem
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
//dialog box code here
}
}

Fragments display getting reset

I have setup a list of fragments using TabLayout and ViewPager on MainActivity as such
public class MainActivity extends AppCompatActivity implements Fragment1.OnFragmentInteractionListener, Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener, Fragment4.OnFragmentInteractionListener
, Fragment5.OnFragmentInteractionListener{
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapater(getSupportFragmentManager(), getApplicationContext()));
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#51ffff"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ced21f"));
break;
case 1:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#51ffff"));
break;
case 2:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private class CustomAdapater extends FragmentPagerAdapter {
private String fragments[] = {"Control", "Connection", "Log", "Others", "Others2"};
public CustomAdapater(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment3();
case 2:
return new Fragment2();
case 3:
return new Fragment4();
case 4:
return new Fragment5();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
}
Somehow when I transit from Fragment1 to Fragment3 and back to Fragment1, the views on Fragment1 gets reset to original state(Like it was just created).
This only happens if I transit 2 fragment away from the current Fragment. For example 2->4 or 3->1.
Everything is fine if the transition is next to each other, for example 2->3 or 1->2.
This is my first android app so do pardon me.
It seems like it is creating a new fragment instead loading of existing ones
Your fragment get destroyed due to the fact that by default viewpager retain only one fragment at a time while moving around so you can simply use
viewPager.setOffscreenPageLimit(no_of_fragment_to_retain);
or
viewPager.setOffscreenPageLimit(3); // in your case
so when you come back from 4->1 or 3->1 you will get the previous stored state of your fragment. link to docs
First :
viewPager.setAdapter(new CustomAdapater(getSupportFragmentManager(), getBaseContext()));
Now see : in get Item method of View pager evrytime when you go to new tab a new instance of fragment is created So the previous view is lost . You should retain state in your fragment class.
or a simple solution is use FragmentstatepagerAdapter instead of FragmentPagerAdapter in your Adapter class.
Let me know if it helps

load multiple tab contents in view pager without getting it again

i have a view pager in tabLayout that getting it's content from a JSON
each page has differ contents
all i want to do is to get each page content once
is there a way to do this
thanks in advance
Yes it's possible. My answer is not from an official source but it's from my previous experience.
Create your ViewPager as a member of the Activity:
private ViewPager pager;
Then inside onCreate() method, initialize your ViewPager:
pager=(ViewPager)findViewById(R.id.pager);
Initialize your tablayout and and a tab selected listener:
tabLayout.addOnTabSelectedListener(
new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition())
{
case 0:
pager.setCurrentItem(0,true);
break;
case 1:
pager.setCurrentItem(1,true);
break;
case 2:
pager.setCurrentItem(2,true);
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
switch (tab.getPosition())
{
case 0:
pager.setCurrentItem(0,true);
break;
case 1:
pager.setCurrentItem(1,true);
break;
case 2:
pager.setCurrentItem(2,true);
break;
}
}
}
);
Set the an adapter to your ViewPager:
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
Create a private inner class MyPagerAdapter that extends FragmentPagerAdapter:
private class MyPagerAdapter extends FragmentPagerAdapter
{
private Tab1 tab1;private Tab2 tab2;private Tab3 tab3;
//Tab1,Tab2,Tab3 representing your respective fragments
public MyPagerAdapter(FragmentManager fm) {
super(fm);
//initialize all your fragments at once inside the constructor
tab1=new Tab1();
tab2=new Tab2();
tab3=new Tab3();
}
#Override
public int getCount() {
return 3;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
//Return each fragment according to a position
switch (position)
{
case 0:
return tab1;
case 1:
return tab2;
case 2:
return tab3;
}
return null;
}
}
That's how I handled my case. Good coding.

Set tab indicator position programatically in TabLayout support library

In my application i am using TabLayout from support library with view pager.I have 3 fragments in it.Suppose i am in fragA which has a button which on clicked takes me to fragB.I am sucessfully going to fragB but only problem is that the tab indicator remains at fragA.
Code
private void setupTablayout() {
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1, true);
tabLayout.getTabAt(0).setIcon(R.drawable.archive).setText("");
tabLayout.getTabAt(1).setIcon(R.drawable.status_1).setText("");
tabLayout.getTabAt(2).setIcon(R.drawable.settings).setText("");
tvHeader.setText("STATUS");
tabLayout.setOnTabSelectedListener(this);
//tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
tab.setIcon(R.drawable.archive_1).setText("");
tvHeader.setText("ARCHIVES");
tvDate.setVisibility(View.GONE);
ivRefresh.setVisibility(View.VISIBLE);
break;
case 1:
tab.setIcon(R.drawable.status_1).setText("");
tvHeader.setText("STATUS");
tvDate.setVisibility(View.VISIBLE);
ivRefresh.setVisibility(View.VISIBLE);
break;
case 2:
tab.setIcon(R.drawable.settings_1).setText("");
tvHeader.setText("SETTINGS");
tvDate.setVisibility(View.GONE);
ivRefresh.setVisibility(View.GONE);
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
tab.setIcon(R.drawable.archive).setText("");
break;
case 1:
tab.setIcon(R.drawable.status).setText("");
break;
case 2:
tab.setIcon(R.drawable.settings).setText("");
break;
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
tab.setIcon(R.drawable.archive).setText("");
break;
case 1:
tab.setIcon(R.drawable.status).setText("");
break;
case 2:
tab.setIcon(R.drawable.settings).setText("");
break;
}
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
// tabLayout.getTabAt(0).setIcon(R.drawable.archive_1).setText("");
// tabLayout.getTabAt(1).setIcon(R.drawable.status).setText("");
// tabLayout.getTabAt(2).setIcon(R.drawable.settings).setText("");
fragment = new ArchivesFrag();
break;
case 1:
// tabLayout.getTabAt(0).setIcon(R.drawable.archive).setText("");
// tabLayout.getTabAt(1).setIcon(R.drawable.status_1).setText("");
// tabLayout.getTabAt(2).setIcon(R.drawable.settings).setText("");
fragment = StatusFrag.newInstance(listPosition);
break;
case 2:
// tabLayout.getTabAt(0).setIcon(R.drawable.archive).setText("");
// tabLayout.getTabAt(1).setIcon(R.drawable.status).setText("");
// tabLayout.getTabAt(2).setIcon(R.drawable.settings_1).setText("");
fragment = new SettingFrag();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
FragA
{
((Home) getActivity()).getArchiveList();
}
Instead of
viewPager.setCurrentItem(tab.getPosition());
You can use,
tab.select();
This worked for me, after trial and error (SDK 23):
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
selectedTab = savedInstanceState.getInt("seltab");
allTabs.getTabAt(selectedTab).select(); // TabLayout
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("seltab",selectedTab);
super.onSaveInstanceState(outState);
}
Note: Set selectedTab when the fragment is loaded...
Have you Created the .Xml file for each Tab.
Main Activity
public class MainActivity extends TabActivity
{
TabHost tabHost;
TabSpec tab1,tab2,tab3,tab4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create the TabHost that will contain the Tabs
tabHost = (TabHost)findViewById(android.R.id.tabhost);
// tabHost.setOnTabChangedListener(this);
TabSpec tab1 = tabHost.newTabSpec("First Tab");
TabSpec tab2 = tabHost.newTabSpec("Second Tab");
TabSpec tab3 = tabHost.newTabSpec("Third tab");
TabSpec tab4 = tabHost.newTabSpec("Fourth Tab");
// Set the Tab name and Activity
// that will be opened when particular Tab will be selected
tab1.setIndicator("",getResources().getDrawable(R.drawable.video));
tab1.setContent(new Intent(this,VideoActivity.class));
//tab1.setIndicator("", getResources().getDrawable(setBackgroundColor(Color.RED)));
tab2.setIndicator("",getResources().getDrawable(R.drawable.images));
tab2.setContent(new Intent(this,ImagesActivity.class));
//tab2.setIndicator("", getResources().getDrawable(setBackgroundColor(Color.RED)));
tab3.setIndicator("",getResources().getDrawable(R.drawable.audio));
tab3.setContent(new Intent(this,AudioActivity.class));
//tab3.setIndicator("", getResources().getDrawable(setBackgroundColor(Color.RED)));
tab4.setIndicator("",getResources().getDrawable(R.drawable.favourites));
tab4.setContent(new Intent(this,Favourites.class));
//tab4.setIndicator("", getResources().getDrawable(setBackgroundColor(Color.RED)));
/** Add the tabs to the TabHost to display. */
tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.addTab(tab3);
tabHost.addTab(tab4);
}
Make Xml For Each Tab/Class And Declare the classes in Manifest

Open fragment from a fragment in android

I have a Activity extending to FragmentActivity which has 4 fragments. I now want to open fragment2 on button click which is present in fragment1.
In short I want to switch from fragment1 to fragment 2 on button click.
My code is:
public class SampleActivity extends FragmentActivity{
static ViewPager mViewPager;
PagingAdapter TabAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new PagingAdapter(getSupportFragmentManager(), this);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(TabAdapter);
}
public class PagingAdapter extends FragmentPagerAdapter {
private Context context;
public PagingAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0:
return context.getString(R.string.page_tab_1);
case 1:
return context.getString(R.string.page_tab_2);
case 2:
return context.getString(R.string.page_tab_3);
case 3:
return context.getString(R.string.page_tab_4);
}
return "Fragment " + (position + 1);
}
}
public class Fragment1 extends Fragment{
Button btn_close = (Button) mydeals.findViewById(R.id.btn_close);
btn_all.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Needs to open fragment2 here.
});
}
I have tried shifting using id but fragment4 is opening by the below code
ViewPager viewpager = DealsActivity.mViewPager;
viewpager.setCurrentItem(getId());
In your Fragment1 layout, add the attribute android:onClick="buttonClickMethod" in your Button definition. Then in your activity, add the following method :
public void buttonClickMethod(View v) {
// some code to execute after button click
// ....
// You can open fragment 2 here, like this :
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.LAYOUT_ID_FOR_FRAGMENT2, FRAGMENT2);
ft.commit();
}
Note that the name of that method is the same one defined in android:onClick attribute.

Categories

Resources