I am having 4 tabs in tablayout and I am using fragments with view pager for them.Now for better customisation,I am providing user a choice to remove any tab or add any tab when they require.
But the problem is now I am not able to remove a tab and add a tab.THe code I have used for making tablayout is mentioned below-
Here objects and reference is passed from Pageradapter class.
public class PagerAdapter extends FragmentStatePagerAdapter {
int NoofTabs;
public PagerAdapter(FragmentManager fm,int NoofTabs) {
super(fm);
this.NoofTabs=NoofTabs;
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
BlankFragment blankFragment=new BlankFragment();
return blankFragment;
case 1:
BlankFragmentia blankFragmentia=new BlankFragmentia();
return blankFragmentia;
case 2:
BlankFragmentyou blankFragmentyou=new BlankFragmentyou();
return blankFragmentyou;
case 3:
Blankt t=new Blankt();
return t;
default:
return null;
}
}
#Override
public int getCount() {
return NoofTabs;
}
}`
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener,BlankFragmentyou.OnFragmentInteractionListener,BlankFragmentina.OnFragmentInteractionListener,Blankt.OnFragmentInteractionListener{
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout=(TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("a"));
tabLayout.addTab(tabLayout.newTab().setText("b"));
tabLayout.addTab(tabLayout.newTab().setText("c"));
tabLayout.addTab(tabLayout.newTab().setText("d"));
tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);
viewPager=(ViewPager)findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(3);
PagerAdapter adapter=new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if(tab.getPosition()==0)
{
tabLayout.setBackgroundColor(Color.parseColor("#3b5998"));
}
else if(tab.getPosition()==1)
{
tabLayout.setBackgroundColor(Color.parseColor("#E91E63"));
}
else if(tab.getPosition()==2)
{
tabLayout.setBackgroundColor(Color.parseColor("#FF0000"));
}
else if(tab.getPosition()==3)
{
tabLayout.setBackgroundColor(Color.parseColor("#00aced"));
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Please help me with adding and removing tabs.Only 4 mentioned above tabs can be used.
Related
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;
}
}
First of all I am new to Android development, and I would appreciate your help.
I have a tabbed activity in android studio and I have a FloatingActionButton to add an Item in each fragment of the tabbed activity. This button then calls a new Activty and I would like to pass to the new activity the tab Number, so that I can store it in a database.
How can I get the tab Number that the new activity was generated from?
Below is the code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_portal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startNewPostActivity = new Intent(getApplicationContext(), NewPostActivity.class);
startNewPostActivity.putExtra("Fragment_Position", position_fragment);
startActivity(startNewPostActivity);
}
});
}
To get the position I was doing the following :
Setting position_fragment = position;
however this returns wrong tab Number.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
position_fragment = position; // not good
return PlaceholderFragment.newInstance(position);
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
}
Try this:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startNewPostActivity = new Intent(getApplicationContext(), NewPostActivity.class);
startNewPostActivity.putExtra("Fragment_Position", mViewPager.getCurrentItem());
startActivity(startNewPostActivity);
}
});
You can identify your tab id from these switch case and call necessary function inside
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
//Log.e("TAG","TAB1");
break;
case 1:
//Log.e("TAG","TAB2");
break;
case 2:
//Log.e("TAG","TAB3");
break;
case 3:
//Log.e("TAG","TAB4");
break;
case 4:
//Log.e("TAG","TAB5");
break;
case 5:
//Log.e("TAG","TAB6");
break;
case 6:
//Log.e("TAG","TAB7");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
There are two ways to get number of the Current Tab in Tabbed Activity
1. use ViewPager.getCurrentItem()
Returns the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state. Defaults to 1.
SAMPLE CODE
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startNewPostActivity = new Intent(getApplicationContext(), NewPostActivity.class);
startNewPostActivity.putExtra("Fragment_Position", mViewPager.getCurrentItem());
startActivity(startNewPostActivity);
}
2. Use TabLayout.addOnTabSelectedListener()
Add a TabLayout.OnTabSelectedListener that will be invoked when tab selection changes.
SAMPLE CODE
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
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
In AppCompatActivity , I can add the code protected void onResume() to launch some function when UI is shown or restored.
Now I created a Tabbed Activity, I add the code protected void onResume() to PlaceholderFragmentOld class , and I hope the system do someting when the UI cleanup_delete_fragment_old is shown, but the system crash and return the following error.
android.support.v4.app.SuperNotCalledException: Fragment PlaceholderFragmentOld{40e55078 #0 id=0x7f0f0070 android:switcher:2131689584:0} did not call through to super.onResume()
PlaceholderFragmentOld.java
public class PlaceholderFragmentOld extends Fragment {
private AdView adView;
private SMSRange mSmsRange;
private View mView;
private Context mContext;
private Spinner spinnerRanger;
private CheckBox chIsWriteLog;
public PlaceholderFragmentOld() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleanup_delete_fragment_old, container, false);
mView=rootView;
mContext=rootView.getContext();
return rootView;
}
#Override
protected void onResume() {
DoSometing();
}
}
CleanupDelete.java
public class CleanupDelete extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cleanup_delete);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch(position){
case 0:
fragment = new PlaceholderFragmentOld();
break;
case 1:
fragment = new PlaceholderFragmentReduce();
break;
case 2:
fragment = new PlaceholderFragmentTrim();
break;
case 3:
fragment = new PlaceholderFragmentPerson();
break;
default:
throw new IllegalArgumentException("Invalid section number");
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.Tab_Old);
case 1:
return getString(R.string.Tab_Reduce);
case 2:
return getString(R.string.Tab_Trim);
case 3:
return getString(R.string.Tab_Person);
}
return null;
}
}
}
Yes, you can add onResume() to a Fragment.
The error your getting states:
SuperNotCalledException: PlaceholderFragmentOld did not call through to super.onResume()
You need to call super.onResume() as the first line in your onResume() method, otherwise the system will complain. Something like this would work
protected void onResume(){
super.onResume();
doSomething();
}
public class PropertyAddActivity extends SherlockFragmentActivity implements OnPageChangeListener, TabListener {
private String TAG="AddActivity: ";
private FileCache fileCache;
private ViewPager mPager;
private ActionBar ab;
private static final int COUNT = 3;
static ArrayList<Integer> mSelectedPropertyType = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.property_add);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
mPager.setOnPageChangeListener(this);
ab = getSupportActionBar();
ab.setDisplayShowTitleEnabled(false);
ab.setDisplayShowHomeEnabled(false);
ab.setNavigationMode(NAVIGATION_MODE_TABS);
GlobalProperty.getInstance().product=new PropertyAdd();
ab.addTab(ab.newTab().setText("Property").setTabListener(this));
ab.addTab(ab.newTab().setText("Property Detail 1").setTabListener(this));
ab.addTab(ab.newTab().setText("Property Detail 2").setTabListener(this));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//listAttachImage.clear();
mSelectedPropertyType.clear();
super.onDestroy();
}
#Override
public void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {
//AppLog.logString(TAG+"onPageScrolled");
}
#Override
public void onPageSelected(int position) {
//AppLog.logString(TAG+"onPageSelected position"+position);
getSupportActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
//AppLog.logString(TAG+"onPageScrollStateChanged ");
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
//AppLog.logString(TAG+"onTabSelected position: "+tab.getPosition());
mPager.setCurrentItem(tab.getPosition());
//ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
//AppLog.logString(TAG+"onTabUnselected");
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
//AppLog.logString(TAG+"onTabReselected");
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
//AppLog.logString(TAG+"COUNT: "+COUNT);
return COUNT;
}
#Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
AppLog.logString(TAG+"position: "+position);
switch (position) {
case 0:
AppLog.logString(TAG+"FRAGGGG1111111");
f = Property1AddFragmentActivity.newInstance(position);
break;
case 1:
AppLog.logString(TAG+"FRAGGGG2222222");
f = Property2AddFragmentActivity.newInstance(position);
break;
case 2:
AppLog.logString(TAG+"FRAGGGGG333333");
f = Property3AddFragmentActivity.newInstance(position);
break;
default:
AppLog.logString(TAG+"Default");
break;
}
return f;
}
}}
i had add add 3 tab Now the problem is that when i set some data in tab1 view and move to tab2 the reselect tab1 the data on tab1 is as it is but when i move to tab3 to tab1 then tab1 data is clear. so cany anyof you have idea to solve this?
At the moment your code appears to be partly action bar tabs and partly ordinary fragments.
If you are trying to use action bar tabs then you need a tab listener. In onTabSelected you should add/replace and in onTabUnselected you should remove.
Please see http://developer.android.com/guide/topics/ui/actionbar.html
section "adding navigation tabs" for a good example.