This question already has answers here:
How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?
(27 answers)
Closed 4 years ago.
I have a working code. I have a TabLayout menu and two items in it. This code works. But when I scroll the screen to the right or left, the other fragment opens. I dont want this. Click on the tab menu and I want the fragment to open. For example, I want A fragment to be opened when A fragment is pushed.
MyFragmentAdapter
public class MyFragmentAdapter extends FragmentPagerAdapter {
int tabCount;
public MyFragmentAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
WebFragment tab1 = new AFragment();
return tab1;
case 1:
PromotionFragment tab2 = new BFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
MyActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** TabLayout and Fragments */
tabLayout = findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("A"));
tabLayout.addTab(tabLayout.newTab().setText("B"));
viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
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) {
}
});
}
}
More simple solution by custom ViewPager to a non swipe ViewPager.
Add this class
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(Context context) {
super(context);
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// Never allow swiping to switch between pages
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
}
in XML layout instead using ViewPager, replace by NonSwipeableViewPager so you can achieve "just click to tab to go to fragment"
Related
So if I have three Fragments A,B, and C.
So when I launch Fragment B I want viewpager to let me swipe from LEFT to RIGHT and it should take me back to Fragment A, but viewpager, by default lets me swipe from RIGHT to LEFT to go to Fragment A.
So basically I want viewpager to let me swipe from LEFT to RIGHT and not from RIGHT to LEFT.
Also I tried:
viewpager.setRotationY=180
That does let me do what I want but all the contents in my Fragments get flipped upside down.
The adapter I am using:
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import org.jetbrains.annotations.NotNull;
public class Adapter extends FragmentPagerAdapter {
public Adapter(FragmentManager fragmentManager){
super(fragmentManager);
}
#NonNull
#NotNull
#Override
public Fragment getItem(int position) {
if(position==0){
return new SettingsFragment();
}
if(position==1){
return new BlankFragment();
}
if(position==2){
return new VersionFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
The activity where I use the adapter:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Fragment fr=new Fragment();
getSupportFragmentManager().beginTransaction().addToBackStack(null).add(fr,"settings_fragment").commit();
runOnUiThread(new Runnable() {
#Override
public void run() {
ViewPager viewPager=findViewById(R.id.ViewPager);
viewPager.setCurrentItem(1);
viewPager.setAdapter(new Adapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(1);
}
});
}
}
I think your code is misleading you, because you using viewPager.setCurrentItem(1); before setAdapter(...) which you ViewPager will not go to item 1 as you expected.
So, try put that viewPager.setCurrentItem(1); after setAdapter(...)
I am trying to create tabs in my android activity,I have done this before,used the same type implementation for this method also
Now in my Activity class in this line final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
I have an error PagerAdapter is abstract; cannot be instantiate I don't know what does that mean
Here is my Activity class code
package com.example.rimapps.icar_iisr_turmeric.view;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.example.rimapps.icar_iisr_turmeric.R;
public class PestsHome extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pests_home);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(R.string.diseases));
tabLayout.addTab(tabLayout.newTab().setText(R.string.insectpescts));
tabLayout.addTab(tabLayout.newTab().setText(R.string.bioagents));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
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) {
}
});
}
}
Then there is another thing in my Adapter class I cannot return my final tab "tab3" it says Required android.support.v4.app.Fragment;
but i have imported that already
here is my adapter class code
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.example.rimapps.icar_iisr_turmeric.view.TabFragment1;
import com.example.rimapps.icar_iisr_turmeric.view.TabFragment2;
import com.example.rimapps.icar_iisr_turmeric.view.TabFragment3;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
please help
Issue is, you have named you customize adapter as PagerAdapter which is also an existing API in android PagerAdapter.
So remove the import
import android.support.v4.view.PagerAdapter;
and carefully import your pageradapter package
Note : It's recommended to avoid naming your classes same as android API
i followed this article http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/ to implement swipe view and it work nice. So now i want to add button on Tab1 and when clicked has to send data to Tab2.
I know there is the issue of using interface but honestly i don't know how to add it on these codes and work provide am completely new to the android.
so far i have tried my best on these links Communication between SlidingTabLayout tabs, How to pass data from one swipe tab to another? and How can I communicate/pass data through different Fragments with Swipe Tab? but i fail.
Any one help please to make it work on every stage , i mean from Tab1 ->Mainactivity->Tab2
thanks alot
Here are the codes after i edit the question
Fragment1
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment1 extends Fragment implements AdapterView.OnItemSelectedListener{
Button send;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.tab_fragment_1, container, false);
send=(Button)v.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// value to be sent to the TabFragment2 on button click
String value=" My Data";
}
});
return v;
}
}
Fragment2
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_2, container, false);
//Display value from TabFragment1
textview.setText(value);
}
}
Interface class
public Interface FragmentCommunication
{
public void printMessage(String message);
}
MainActivity
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements FragmentCommunication{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
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) {
}
});
}
public void printMessage(String message)
{
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
}
}
Adapter Class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
so after posting more code I'm answering:
Implement some FragmentCommunication for both your Fragments:
//public class TabFragment1 extends Fragment implements FragmentCommunication{
public class TabFragment2 extends Fragment implements FragmentCommunication{
//public static final String TAG="TabFragment1";
public static final String TAG="TabFragment2";
...
#Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if(getActivity() instanceOf MainActivity)
((MainActivity) getActivity()).registerFragmentCommunication(
TAG, this);
}
#Override
public void printMessage(String message){
Toast.makeText(getActivity(), TAG+" says: "+message,
Toast.LENGTH_SHORT).show();
}
}
note this line inside onActivityCreated:
((MainActivity) getActivity()).registerFragmentCommunication(TAG, this);
this means implemented FragmentCommunication, TAG will be unique key/name of Fragment and whole method is registration of your interface in Activity. so now you have to add registerFragmentCommunication method to your MainActivity and keep reference to passed interfaces, e.g. in HashMap:
HashMap<String, FragmentCommunication> fragmentCommunications =
new HashMap<String, FragmentCommunication>();
...
public void registerFragmentCommunication(String key, FragmentCommunication fc){
fragmentCommunications.put(key, fc);
}
so now you can access each FragmentCommunication of both fragments from your MainActivity, e.g by using method like this:
public void callFragmentCommunication(String key, String msg){
if(fragmentCommunications.get(key)!=null)
fragmentCommunications.get(key).printMessage();
}
callFragmentCommunication(TabFragment1.TAG, "hi!");
callFragmentCommunication(TabFragment2.TAG, "hi!");
method is public, so Fragments can call it simply like this:
//inside TabFragment1
if(isAdded() && getActivity()!=null &&
getActivity() instanceOf MainActivity &&
!getActivity().isFinishing())
((MainActivity) getActivity()).callFragmentCommunication(
TabFragment2.TAG, "hi!");
this will show Toast with text: "TabFragment2 says: hi!", which was called inside TabFragment1. now you may pass another kind of data as well :)
there is much more methods like communicating through FragmentStatePagerAdapter like here, passing Bundle arguments where fragments are initialized, additional feedback interfaces (e.g. returning true/false when message was passed) etc. Above is just very simplified way, good luck with improving it! :)
I know there are several other posts on this topic, but I wanted to paste my code because I believe there may be an error in it that is causing my problem. My FragmentStatePagerAdapter is returning the wrong position, and I am not sure why.
Here is the code in my Main activity.
Main.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.microsoft.windowsazure.notifications.NotificationsManager;
import java.util.ArrayList;
public class Main extends AppCompatActivity {
public static TextView txtViewHeading;
public static TextView tab1TabBadge;
public static TextView tab2TabBadge;
public static TextView tab3TabBadge;
public static TextView tab4TabBadge;
public static TextView tab5TabBadge;
public static Button btnBack;
public static ImageButton btnShare;
public static Main mainActivity;
public static Context mainActivityContext;
public static Boolean isVisible = false;
private FragmentTabHost mTabHost;
private GoogleCloudMessaging gcm;
private ActionBar actionBar;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private TabGroupAdapter mTabGroupAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set up Push notifications
mainActivity = this;
mainActivityContext = Main.this;
NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, PushHandler.class);
registerWithNotificationHubs();
// Set up the views for each tab - custom view used for Badge icon
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Bind the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Set up the ActionBar
actionBar = getSupportActionBar();
if (actionBar!=null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
// Create the adapter that will return a fragment for each of the primary "tabs"
mTabGroupAdapter = new TabGroupAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mTabGroupAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
// tab1 Tab
View tab1TabView = inflater.inflate(R.layout.tab, null);
ImageView tab1TabIcon = (ImageView) tab1TabView.findViewById(R.id.tabIcon);
tab1TabIcon.setImageResource(R.drawable.tab_first);
TextView tab1TabText = (TextView) tab1TabView.findViewById(R.id.tabText);
tab1TabText.setText("tab1");
tab1TabText.setTypeface(arialTypeface);
tab1TabBadge = (TextView) tab1TabView.findViewById(R.id.tabBadge);
tab1TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(0).setCustomView(tab1TabView);
// Also set this tab as Active be default
tabLayout.getTabAt(0).getCustomView().setSelected(true);
mViewPager.setCurrentItem(0);
// tab2 Tab
View tab2TabView = inflater.inflate(R.layout.tab, null);
ImageView tab2TabIcon = (ImageView) tab2TabView.findViewById(R.id.tabIcon);
tab2TabIcon.setImageResource(R.drawable.tab_second);
TextView tab2TabText = (TextView) tab2TabView.findViewById(R.id.tabText);
tab2TabText.setText("Odometer");
tab2TabText.setTypeface(arialTypeface);
tab2TabBadge = (TextView) tab2TabView.findViewById(R.id.tabBadge);
tab2TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(1).setCustomView(tab2TabView);
// tab3 Tab
View tab3TabView = inflater.inflate(R.layout.tab, null);
ImageView tab3TabIcon = (ImageView) tab3TabView.findViewById(R.id.tabIcon);
tab3TabIcon.setImageResource(R.drawable.tab_third);
TextView tab3TabText = (TextView) tab3TabView.findViewById(R.id.tabText);
tab3TabText.setText("tab3");
tab3TabText.setTypeface(arialTypeface);
tab3TabBadge = (TextView) tab3TabView.findViewById(R.id.tabBadge);
tab3TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(2).setCustomView(tab3TabView);
// tab4 Tab
View tab4TabView = inflater.inflate(R.layout.tab, null);
ImageView tab4TabIcon = (ImageView) tab4TabView.findViewById(R.id.tabIcon);
tab4TabIcon.setImageResource(R.drawable.tab_fourth);
TextView tab4TabText = (TextView) tab4TabView.findViewById(R.id.tabText);
tab4TabText.setText("tab4");
tab4TabText.setTypeface(arialTypeface);
tab4TabBadge = (TextView) tab4TabView.findViewById(R.id.tabBadge);
tab4TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(3).setCustomView(tab4TabView);
// tab5 Tab
View tab5TabView = inflater.inflate(R.layout.tab, null);
ImageView tab5TabIcon = (ImageView) tab5TabView.findViewById(R.id.tabIcon);
tab5TabIcon.setImageResource(R.drawable.tab_fifth);
TextView tab5TabText = (TextView) tab5TabView.findViewById(R.id.tabText);
tab5TabText.setText("tab5");
tab5TabText.setTypeface(arialTypeface);
tab5TabBadge = (TextView) tab5TabView.findViewById(R.id.tabBadge);
tab5TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(4).setCustomView(tab5TabView);
// Tab listener
/*
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
txtViewHeading.setText(tab.getText());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
*/
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if(mViewPager.getCurrentItem()==0){
onBackPressed();
}
else{
mViewPager.setCurrentItem(mViewPager.getCurrentItem()-1);
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
isVisible = false;
}
#Override
protected void onResume() {
super.onResume();
isVisible = true;
}
#Override
protected void onStop() {
super.onStop();
isVisible = false;
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
ToastNotify("This device is not supported by Google Play Services.");
finish();
}
return false;
}
return true;
}
public void ToastNotify(final String notificationMessage) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Main.this, notificationMessage, Toast.LENGTH_LONG).show();
}
});
}
private void registerWithNotificationHubs()
{
if (checkPlayServices()) {
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
}
...and here is the code for my FragmentStatePagerAdapter
TabGroupAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import java.util.ArrayList;
public class TabGroupAdapter extends FragmentStatePagerAdapter {
private static int fragmentSize = 5;
private static ArrayList<String> fragmentTitles = new ArrayList<String>() {
{
add("tab1");
add("tab2");
add("tab3");
add("tab4");
add("tab5");
}
};
public TabGroupAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d("tag","POSITION: " + position);
switch (position) {
case 0:
default:
return new Tab1Fragment();
case 1:
return new Tab2Fragment();
case 2:
return new Tab3Fragment();
case 3:
return new Tab4Fragment();
case 4:
return new Tab5Fragment();
}
}
#Override
public int getCount() {
return fragmentSize;
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitles.get(position);
}
}
To sum it up, when my app loads, the first tab is empty. Just a blank screen. It is not my Tab1Fragment as it should be. Also when I click through my tabs, the position should show from left to right 0,1,2,3,4 as I have 5 tabs. It does not though. I have a Log.d statement in my getItem(position) method in which I am logging the current position to the console. When my app loads it shows Position:0, then Position:1 all on load, which is weird since it should only show position 0 since that is the default tab (tab1). Then when I click through, tab 2 shows position 2, tab 3 shows position 3, tab 4 shows position 4 and tab 5 does not log at all. Then working back from tab 5 to tab 1, the positions are all out of whack, and when I get to tab 1 it does not log. It's quite strange. Also, my back arrow in my fragment that SHOULD only show up if I am not at the root fragment of the tab, instead shows up all the time.
Can anyone please help me figure out why this is happening?
If any more code is needed to determine the problem, I am happy to post it just please let me know what you need to see.
Try commenting out all of the code beneath:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
in your onCreate method. Run again and see what happens.
Your switch statement is laid out in a strange way, too. If you'll definitely only have 5 cases, then it should go from case 0-4, with a default case at the end that prints an error to the log, or throws an exception. I don't think this will be causing your issue, but it's good practice.
Also it's usually not a good idea to instantiate fragments using the default constructor. A better way is to use a static factory method, ie:
Tab1Fragment fragment = Tab1Fragment.create();
return fragment;
With a static create() method in your fragment, that initialises the object. It gives you a single access point to fragment, and means that any initialisation you need to do (now or at some point down the line) can all be done in once place, making you less prone to error. Android also re-creates fragments using the default constructor, so any initialisation you come to do in an overloaded constructor will be ignored. Again I don't think this is the cause of your issue, but it's worth bearing in mind.
Edit: In addition, when you say it is choosing random fragments "The position will show 0,3,2,0,4,1 just random numbers", do you mean those are the fragments being displayed on screen, or are those the positions you're logging from the "getItem(int position)" argument?
viewPager = (ViewPager) findViewById(R.id.tabPager);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(),"fragment 1");
adapter.addFragment(new Fragment2(),"fragment 2");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
return position;
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
assert tabLayout != null;
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
Then in your 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);
}
}
hello
could you please tell me why on landscape it is not acquiring equal width as in portrait mode ?? is there any way to provide equal width into tabs in portrait mode.
I do like this
landscape
potrait
here is my code ..in portrait it is taking equal width but on landscape it is not taking the equal width why ?
here is my code
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
ActionBar actionBar;
ViewPager viewPager;
PageAdapter pageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
pageAdapter =new PageAdapter(getSupportFragmentManager());
viewPager.setAdapter(pageAdapter);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("Tab1").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab2").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab3").setTabListener(this));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
Adapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PageAdapter extends FragmentPagerAdapter{
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new Fragmentone();
case 1:
return new Fragmenttwo();
case 2:
return new FragmentThree();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}