Getting the number of the Current Tab in Tabbed Activity - android

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

Related

How can I open another activity with specific fragment with Navigation Component?

I am using two Activities. One is MainActivity and the second one is for NFC. MainActivity has nav_graph.xml.
After reading the NFC, I'd like to start MainActivity and move to a certain fragment of MainActivity.
How can I implement this?
You can try this:
(in MainActivity.java)
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
Frag1 frag1 = new Frag1();//this is one activity
return frag1;
case 1:
Frag2 frag2 = new Frag2();
return frag2;
default:
return null;
}
}
#Override
public int getCount() {
return 2; //'the number 2 is 'cause you've got a two activities
}
}
and if you want open another activity with de floating action button, you can try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mViewPager.getCurrentItem()==0){
Fragment1();
Toast.makeText(MainActivity.this, "Example 1", Toast.LENGTH_SHORT).show();
}else if(mViewPager.getCurrentItem()==1){
Fragmen2();
Toast.makeText(MainActivity.this, "Example 2", Toast.LENGTH_SHORT).show();
}
}
});
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
public void Fragment1(){//Call to the activity Example1
Intent fragment0 = new Intent(getApplicationContext(), example1.class);
startActivity(fragment0);
onResume();
}
public void Fragmen2(){ //Call to the activity Example2
Intent fragment1 = new Intent(getApplicationContext(), example2.class);
startActivity(fragment1);
onResume();
}

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

Removing and adding specific tab in ViewPager tablayout

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.

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

How can I implement OnClickListener of an ImageView in a fragment?

Can anyone kindly help me implement the opening of a new activity upon clicking of an ImageView. I have a code snippet displayed below.
public class TabFan extends Fragment {
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.tab_fan, container, false);
// Onclick Listening
ImageView image = (ImageView) findViewById(R.id.image);
image.setOnClickListener(this);
}
public void onClick(View v) {
// Launching new Activity on hitting the image
Intent j = new Intent(getApplicationContext(), Activity2.class);
startActivity(j);
// End intent
}
}
Ok I have a code with three tabs, the following controls my tabs which is working right.
public class Fans extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fans);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Fans"));
tabLayout.addTab(tabLayout.newTab().setText("Jersey"));
tabLayout.addTab(tabLayout.newTab().setText("Team"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
});
}
#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) {
}
}
I have another class pager
public class Pager extends FragmentStatePagerAdapter {
//integer to count number of tabs
int tabCount;
//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
TabFan tab1 = new TabFan();
return tab1;
case 1:
TabJersey tab2 = new TabJersey();
return tab2;
case 2:
TabTeam tab3 = new TabTeam();
return tab3;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
}
Finally the interested raw class TabFan, now where exactly should that listener be implemented. I have tried the class Fans but apparently am getting some crush, TabFan seem not to work with the events too. Any help please.
public class TabFan extends Fragment {
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.tab_fan, container, false);
// Onclick Listener
}
}
With the code that you have provided, you will need to do two things to properly link the image object to the onClick() method that you have written.
First, the Fragment class needs to implement the View.OnClickListener interface. This is what makes the onClick(View v)actually activate on a click when using setOnClickListener(this). Replace your class declaration line with:
public class TabFan extends Fragment implements View.OnClickListener {
Second, if you are going to add any more clickable objects to TabFan with setOnClickListener(this), then onClick(View v) needs to verify that it is dealing with the expected View:
#Override
public void onClick(View v) {
if (v.getId() == R.id.image) {
// Launching new Activity on hitting the image
Intent j = new Intent(getActivity().getApplicationContext(), Activity2.class);
startActivity(j);
// End intent
}
}
If you click Ctrl + Space keys, Android Studio will show you suggestion window and generate overriding methods like onClick for you.
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(getActivity(), Activity2.class);
startActivity(j);
}
});
Doesn't matter where you are, in Fragment or in Activity. ImageView just needs View.OnClickListener. for detecting click events override onClick method.
And another point when you need any context in fragment use getActivity() or getActivity().getApplicationContext()
What I like to do is setting up the onClick in the XML already like this:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="yourMethod"
android:src="#drawable/yourpicture"/>
Then in your Fragment or Activity just implement yourMethod to open the new Activity:
public void yourMethod(View v) {
Intent intent = new Intent(this, ToOpenAcitivy.class);
startActivity(intent);
}
Also this site helped me a lot when learning about stuff like this.

Categories

Resources