Fragment Not Replaced In ViewPager - android

I am trying to replace a fragment displayed in a tab using TabLayout and ViewPager as shown below:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.netstreamtech.phonebuylogin.LoginRegisterActivity"
android:paddingLeft="32.5dp"
android:paddingTop="27dp"
android:paddingRight="30dp">
<LinearLayout
android:id="#+id/main_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/signInReOtpHeader"
android:layout_width="268dp"
android:layout_height="122dp"
android:includeFontPadding="true"
android:maxLines="2"
android:text="Welcome \nback."
android:layout_gravity="center_vertical"
android:textColor="#1aa4b8"
android:textSize="35sp" />
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="wrap_content"
android:layout_height="47dp"
android:minHeight="?attr/actionBarSize"
android:elevation="6dp" />
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
From my Fragment:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof RegisterMainToActivity) {
listener = (RegisterMainToActivity) context;
}
}
Then later in the same fragment:
listener.passData(userRegistration);
The Interface:
public interface RegisterMainToActivity {
void passData(UserRegistration data);
}
In My Activity(LoginRegisterActivity):
public class LoginRegisterActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener, RegisterMainToActivity {
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
private LoginPager adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_register);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
createViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
createTabIcons();
}
private void createTabIcons() {
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.login_cutom_tab_view, null);
tabOne.setText("SIGN IN");
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.login_cutom_tab_view, null);
tabTwo.setText("REGISTER");
tabLayout.getTabAt(1).setCustomView(tabTwo);
}
private void createViewPager(ViewPager viewPager) {
adapter = new LoginPager(getSupportFragmentManager());
adapter.addFrag(new Login(), "SIGN IN");
adapter.addFrag(new RegisterMain(), "REGISTER");
viewPager.setAdapter(adapter);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//tabLayout.setBackground(getResources().getDrawable(R.drawable.login_tab_selected));
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//tabLayout.setBackground(getResources().getDrawable(R.drawable.login_tab_unselected));
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void passData(UserRegistration data) {
RegisterOtp registerOtpFrag = new RegisterOtp();
adapter.replaceFragment(registerOtpFrag, 1, "REGISTER");
//adapter = new LoginPager(getSupportFragmentManager());
//adapter.addFrag(new Login(), "SIGN IN");
//adapter.addFrag(new RegisterOtp(), "REGISTER");
//adapter.clearFragments();
//adapter.addFrag(new Login(), "SIGN IN");
//adapter.addFrag(new RegisterOtp(), "REGISTER");
//viewPager.setAdapter(adapter);
createTabIcons();
}
// public void attemptRegister(View v){
// TextView registerName = (TextView) v.getContext()findViewById(R.id.register_name);
// Toast.makeText(
// getApplicationContext(),
// registerName.getText(),
// Toast.LENGTH_SHORT
// ).show();
// }
}
In the function passData , I am trying to replace a fragment. I want this added to the backstack.
In my adapter class:
public class LoginPager extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public LoginPager(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void replaceFragment(Fragment fragment, int index, String title) {
mFragmentList.remove(index);
mFragmentList.add(index, fragment);
mFragmentTitleList.add(title);
notifyDataSetChanged();
}
public void clearFragments()
{
mFragmentList.clear();
notifyDataSetChanged();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return this.POSITION_NONE;
}
}
I have tried many variations, including trying to clear the adapter and recreate the fragments. Whatever I do I am not able to replace the desired Fragment(RegisterMain with RegisterOtp). Ideally I should just be able to replace it... Please help!!!

FragmentStatePagerAdapter works for me.
public class LoginPager extends FragmentStatePagerAdapter {...}
FragmentPagerAdapter.notifyDataSetChanged() didn't clear those already committed fragments.
FragmentPagerAdapter is best for use when there are a handful of
typically more static fragments to be paged.

Related

how to override and display title of tabs in viewpager2 in tablayout

I am using a TabLayout inside a Fragment. The content of the TabLayout (made of 2 fragments) is displayed but not the title of the tabs. I believe it's a layout problem but i'm not sure on how to fix it.
Also what would be the overrided method for ViewPager2 that was used in ViewPager (getPagetitle) ?
main Fragment
public class CommunityFragment extends Fragment {
private TabLayout tbL;
private ViewPager2 vp;
private RecipeViewPagerAdapter rvpa;
public CommunityFragment() {
// Required empty public constructor
}
public static CommunityFragment newInstance(){
return new CommunityFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_community, container, false);
tbL = rootView.findViewById(R.id.tabL);
vp = rootView.findViewById(R.id.pager);
rvpa = new RecipeViewPagerAdapter(this);
vp.setAdapter(rvpa);
rvpa.addFragment(new AllFragment(),"All time");
rvpa.addFragment(new DayFragment(),"Today");
new TabLayoutMediator(tbL, vp, new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
//////title????
}
}).attach();
return rootView;
}
}
Adapter
public class RecipeViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> listF = new ArrayList<>();
private ArrayList<String> listT = new ArrayList<>();
public RecipeViewPagerAdapter(#NonNull Fragment fragment) {
super(fragment);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return listF.get(position);
}
//new method ????
public CharSequence getPageTitle(int position){
return listT.get(position);
}
#Override
public int getItemCount() {
return listT.size();
}
public void addFragment(Fragment frag, String title){
listF.add(frag);
listT.add(title);
}
}
fragment layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".fragments.CommunityFragment">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
app:tabIndicatorColor="#color/yellowCool"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
put this in your main activity....
myAdapter=new FragmentAdapter(this);
myViewPager2.setAdapter(myAdapter);
String [] tabTtiles={"Home","Chat","Notification","Account"};
new TabLayoutMediator(myTabLayout, myViewPager2,(myTabLayout, position) ->
myTabLayout.setText(tabTtiles[position])).attach();
Your tabLayout doesn't display. Use this:
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" // add this line
/>
TabLayoutMediator:
new TabLayoutMediator(tbL, vp, new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
if(position == 0)
tab.setText("All time");
else
tab.setText("Today");
}
}).attach();
You can use the following adapter for the viewPager2:
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 10;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull #Override public Fragment createFragment(int position) {
return CardFragment.newInstance(position);
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
}
on the mainActivity you need to have something inline with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
}
}
As per documentation:
The TabLayoutMediator object also handles the task of generating page
titles for the TabLayout object, which means that the adapter class
does not need to override getPageTitle():
And to do that:
TabLayout tabLayout = view.findViewById(R.id.tab_layout);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText("OBJECT " + (position + 1))
).attach();

I want to show tab bar icon left side of text

I want to show icon left side of the text but the problem is that the icon is showing above the text. it's taking much more space.
I want keep the icon left sode of the text(title) . what should i do?
The main activity is given below
java.class
public class Tabsadar extends AppCompatActivity {
ExpandableRelativeLayout
expandableLayout1,
expandableLayout2,
expandableLayout3,
expandableLayout4;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_name,
R.drawable.thanatottho,
R.drawable.proyojonio
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabsadar);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new tabsadarc1(), "ফিচার");
adapter.addFrag(new tabsadarc2(), "তথ্যাবলি");
adapter.addFrag(new tabsadarc3(), "প্রয়োজনীয়");
viewPager.setAdapter(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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}'
i want something like that
in my case something happend like that
any solution?
Just use app:tabInlineLabel="true"
Like:-
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabInlineLabel="true"
app:tabGravity="fill"/>
As per your requirement I'll suggest you to create a custom view for tabs.
custom_tab_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/_6sdp"
android:background="#drawable/ic_menu_gallery"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="#dimen/_3sdp"
android:textColor="#drawable/tab_text_selector"
android:textSize="#dimen/_15sdp" />
</LinearLayout>
</RelativeLayout>
And this layout of custom tab with PagerAdapter as
//On Create
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
View customView = mPagerAdapter.getCustomView(getActivity(), i);
mainTabLayout.getTabAt(i).setCustomView(customView);
}
//Pager Adapter
public static class ViewPagerAdapter extends SmartFragmentStatePagerAdapter {
private List<Map<String, Object>> maps = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
ImageView imageView = (ImageView) mView.findViewById(R.id.imageView);
mTextView.setGravity(Gravity.CENTER);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(),
"fonts/aller_regular.ttf"));
mTextView.setText(getPageTitle(pos));
return mView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CompletedTaskFragment();
case 1:
return new PendingTaskFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
Hope it'll help you.

Issue while changing fragment in ViewPager

I am trying to change/slide fragment on click of a button in ViewPager. My code works in one project but, not in current.
xml of activity to load fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="firebasetest.imranrana.android.firebasetest.SwipeActivity"
tools:showIn="#layout/activity_swipe"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPagerId"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
activity:
public class SwipeActivity extends AppCompatActivity{
ViewPager viewPager;
Toolbar toolbar;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().hide();
viewPager=(ViewPager)findViewById(R.id.viewPagerId);
setupViewPager(viewPager);
// tabLayout=(TabLayout)findViewById(R.id.tabLayoutId);
// tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new WebViewFragment()/*, "Main"*/);
adapter.addFragment(new MenuFragment()/*, "TWO"*/);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
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);
}*/
}
}
fragment of viewpager contains changing button:
public class MenuFragment extends Fragment {
Button funPageButton;
Button profilePageButton;
Fragment fragment;
FragmentTransaction fragmentTransaction;
public MenuFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_menu, container, false);
funPageButton=(Button)view.findViewById(R.id.funPageButtonId);
profilePageButton=(Button)view.findViewById(R.id.profileButtonId);
funPageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"test",Toast.LENGTH_LONG).show();
fragment=new TestFragment();
fragmentTransaction=getActivity().getSupportFragmentManager().beginTransaction(); ;
fragmentTransaction.replace(R.id.content_swipe,fragment).commit();
}
});
profilePageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"test 1",Toast.LENGTH_LONG).show();
fragment=new TestFragment1();
fragmentTransaction=getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_swipe,fragment).commit();
}
});
return view;
}
}
What am i doing wrong?

Tabs with in the Tabs in android studio

I just want to implements Tabs with in the Tabs. If it is possible than please share the code
See image below for reference
This is the answer of my question. I set the tabs with in the Tabs. Basically set the tab in fragment:
My java code:
public class SD extends Fragment {
View view;
PagerAdapter adapter;
public SD() {
// Required empty public constructor
}
private void setupViewPager(ViewPager viewPager) {
///Here we have to pass ChildFragmentManager instead of FragmentManager.
adapter = new PagerAdapter(getChildFragmentManager());
adapter.addFragment(new Sim1Detail(), "Sim 1");
adapter.addFragment(new Sim2Detail(), "Sim 2");
viewPager.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.sd, container, false);
super.onCreate(savedInstanceState);
// ButterKnife.bind(getActivity(), view);
final ViewPager viewPager = ButterKnife.findById(view, R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = ButterKnife.findById(view, R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// ButterKnife.unbind(getActivity);
}
static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
here it is ..

How to load the fragments when the tab is selected or page is swiped

when I am swiping tabs are changing but fragment that I attached is not loading.
I have created 4 fragments and their layouts
I have included pagerAdapter in the mainActivity class
output(showing blank page when tab is selected)
Here is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "Home");
adapter.addFragment(new FragmentTwo(), "e-Profile");
adapter.addFragment(new FragmentThree(), "Results");
adapter.addFragment(new FragmentFour(), "Outpass");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
onTabSelectedListener(viewPager);
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
}
this is my viewpagerAdapter.
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);
}
}
MyFragment
public class FragmentOne extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
Please follow the following code it will work.Compare ur code with this.It will perfectly work for me.
My Activity:
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager viewPager) {
return 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) {
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
onTabSelectedListener(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
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);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
OneFragment.java
public class OneFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.frag_one,container,false);
return inflater.inflate(R.layout.frag_one,container,false);
}
}
frag_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="First Fragment"/>
</LinearLayout>
Same like on your code ontabselected you set current item of viewpager here also in on pageselected you have to replace your fragment
eventPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
if (arg0 == 0) {
// replace fragmen1
}
if (arg0 == 1) {
// replace fragment 2
}
if (arg0 == 2) {
// replace fragment 3
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Remove these line of codes and it should work.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
onTabSelectedListener(viewPager);
Return the view properly in fragment:) Woolla it should work:)
public class ThreeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_three,container,false);
return view;
}
}

Categories

Resources