Set tab indicator position programatically in TabLayout support library - android

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

Related

Tabs in Android disappears. Code was working before but now it stopped working

I have used Tab Control and RecyclerView together in Android. The way it functions is I have SearchBar in the toolbar. When the user enters the search query in the search bar. Upon hitting the search button, tab's Fragments are supposed to be loaded with data. Issues are as follows.
1) Tabs icon disappear
2) When debugging through the code found (Since I am using ViewPager with Tab Layout to implement Tabs in android) that getItem method of PagerAdapter class is called twice every time getItem is triggered.
I am stuck and don't know what to do. Not much help online as well.
1) Tab initialization Code:-
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.craigslist_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.kijiji_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.letgo_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.varagesale_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.facebook_new1));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
drawerLayout = findViewById(R.id.drawer_layout);
}
#Override
public boolean onQueryTextSubmit(String query) {
//loadRecyclerViewData(query);
Bundle bundle = new Bundle();
bundle.putString("searchText", query);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), bundle);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return true;
}
2) PagerAdapter:-
public class PageAdapter extends FragmentStatePagerAdapter {
int mNoofTabs;
Bundle bundle;
public PageAdapter(FragmentManager fragmentManager, int NumberOfTabs, Bundle bundle)
{
super(fragmentManager);
this.mNoofTabs = NumberOfTabs;
this.bundle = bundle;
}
#Override
public Fragment getItem(int i) {
switch(i)
{
case 0 :
CraigslistFragment tab1 = new CraigslistFragment();
tab1.setArguments(bundle);
return tab1;
case 1:
KijijiFragment tab2 = new KijijiFragment();
tab2.setArguments(bundle);
return tab2;
case 2:
letgoFragment tab3 = new letgoFragment();
tab3.setArguments(bundle);
return tab3;
case 3:
VaragesaleFragment tab4 = new VaragesaleFragment();
tab4.setArguments(bundle);
return tab4;
case 4:
FacebookFragment tab5 = new FacebookFragment();
tab5.setArguments(bundle);
return tab5;
default:
return null;
}
}
#Override
public int getCount() {
return mNoofTabs;
}
}

how to replace fragments on tab?

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);

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

when i open my app , how to avoid BottomBar automatically selected AboutusTab?

when i open my application,default selected Home_Tab is opened,working fine....but in this Home_Tab,Bottombar also there ,i dont want default selection tab of About Us??
if i want click AboutUs_Tab that time it will open???
but in this above image when i open Home_Tab ,automatically selected AboutUs_Tab but not opened it ,will try to click that aboutUs_Tab not working???
When i click ContactUS_Tab and return to AboutUs_Tab ,that time AboutUS_Tab opened??how to avoid this issue??
this is my code
public class MainActivity extends FragmentActivity {
private Context context;
//This is our tablayout
private TabLayout tabLayout;
BottomBar bottombar;
//This is our viewPager
private ViewPager viewPager;
public ViewPagerAdapter FragmentStatePagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setHasOptionsMenu(true);
bottombar = BottomBar.attach(MainActivity.this, savedInstanceState);
bottombar.noNavBarGoodness();
bottombar.setItemsFromMenu(R.menu.bottom_bar_menu, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(int itemId) {
switch (itemId) {
case R.id.about_us:
About_Us about_us = new About_Us();
About_Fragment about_fragment = new About_Fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.Home_BottomBar_Fragment, about_fragment).commit();
break;
case R.id.contact_us:
ContactUs_Activity contactUs_activity = new ContactUs_Activity();
Contact_us_Fragment contact_us_fragment = new Contact_us_Fragment();
FragmentManager fm2 = getSupportFragmentManager();
FragmentTransaction ft2 = fm2.beginTransaction();
ft2.replace(R.id.Home_BottomBar_Fragment, contact_us_fragment).commit();
//squareFragment.updateColor(Color.parseColor(colors[1]));
//Toast.makeText(MainActivity.this,"selected contact_us",Toast.LENGTH_SHORT).show();
break;
case R.id.donate_us:
Donate_us_Fragment donate_us_fragment = new Donate_us_Fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.Home_BottomBar_Fragment, donate_us_fragment).commit();
//Toast.makeText(MainActivity.this,"selected donate_us",Toast.LENGTH_SHORT).show();
break;
default:
}
}
});
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Home").setIcon(R.drawable.home_selector));
tabLayout.addTab(tabLayout.newTab().setText("News").setIcon(R.drawable.news_selector));
tabLayout.addTab(tabLayout.newTab().setText("Videos").setIcon(R.drawable.video_selector));
tabLayout.addTab(tabLayout.newTab().setText("PodCasts").setIcon(R.drawable.podcast_selector));
tabLayout.addTab(tabLayout.newTab().setText("More").setIcon(R.drawable.more_selector));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//tabLayout.setupWithViewPager(viewPager);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
bottombar.show();
//bottombar.getCurrentTabPosition();
} else if (tab.getPosition() == 1) {
bottombar.hide();
} else if (tab.getPosition() == 2) {
bottombar.hide();
} else if (tab.getPosition() == 3) {
bottombar.hide();
}else if (tab.getPosition() == 4){
bottombar.hide();
}
super.onTabSelected(tab);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
//tab.getIcon().setAlpha(127);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outstate) {
super.onSaveInstanceState(outstate);
// Necessary to restore the BottomBar's state, otherwise we would
// lose the current tab on orientation change.
bottombar.onSaveInstanceState(outstate);
}
}
You can manually set the default selected tab in bottom bar with:
bottomBar.setDefaultTabPosition(1);
Use this after initializing the bottom bar.
You need to add one dummy invisible item for make your thinks work. For that create one more item :
<item android:id="#+id/none"
android:title=""/>
where you create your items. And then in your code change to this :
bottombar.setItemsFromMenu(R.menu.bottom_bar_menu, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(int itemId) {
switch (itemId) {
case R.id.none:
break;
case R.id.about_us:
About_Us about_us = new About_Us();
About_Fragment about_fragment = new About_Fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.Home_BottomBar_Fragment, about_fragment).commit();
break;
case R.id.contact_us:
ContactUs_Activity contactUs_activity = new ContactUs_Activity();
Contact_us_Fragment contact_us_fragment = new Contact_us_Fragment();
FragmentManager fm2 = getSupportFragmentManager();
FragmentTransaction ft2 = fm2.beginTransaction();
ft2.replace(R.id.Home_BottomBar_Fragment, contact_us_fragment).commit();
//squareFragment.updateColor(Color.parseColor(colors[1]));
//Toast.makeText(MainActivity.this,"selected contact_us",Toast.LENGTH_SHORT).show();
break;
case R.id.donate_us:
Donate_us_Fragment donate_us_fragment = new Donate_us_Fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.Home_BottomBar_Fragment, donate_us_fragment).commit();
//Toast.makeText(MainActivity.this,"selected donate_us",Toast.LENGTH_SHORT).show();
break;
default:
}
}
});

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.

Categories

Resources