This is my manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
This is my some part of MainActivity.java
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment,recepie_fragment,products_fragment,swadeshi_fragment,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_yash);
//setSupportActionBar(toolbar);
//setSupportActionBar(null);
// final View ab=(View)findViewById(R.id.appbarmain);
fragmentManager = getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
recepie_fragment=new Recepie_Fragment();
products_fragment=new Products_Fragment();
swadeshi_fragment=new Swadeshi_Fragment();
fragment=recepie_fragment;//new Fragment();
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
previous=fragment;
BottomBar bb=BottomBar.attach(this,savedInstanceState);
bb.setActiveTabColor("RED");
bb.setItemsFromMenu(R.menu.bottom_buttons, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(int menuItemId) {
fragmentTransaction=fragmentManager.beginTransaction();
switch(menuItemId)
{
case R.id.button1:
previous=fragment;
// ab.setAlpha(0);
fragment=recepie_fragment;//new Recepie_Fragment();
// fragment.setRetainInstance(true);
break;
case R.id.button2:
//getSupportActionBar().show();
previous=fragment;
fragment=products_fragment;//new Products_Fragment();
//fragment.setRetainInstance(true);
break;
case R.id.button3:
previous=fragment;
//getSupportActionBar().show();
fragment=swadeshi_fragment;//new Swadeshi_Fragment();
//fragment.setRetainInstance(true);
break;
}
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
}
});
}
Here is my RecepieFragment.java
public class Recepie_Fragment extends Fragment {
View rootView;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
int logo_ids[]={R.drawable.main_course,R.drawable.cakes,R.drawable.specials};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void setupTabIcons()
{
tabLayout.getTabAt(0).setIcon(logo_ids[0]);
tabLayout.getTabAt(1).setIcon(logo_ids[1]);
tabLayout.getTabAt(2).setIcon(R.drawable.extra);
// tabLayout.getTabAt(1).setCustomView();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//getActivity().getApplication().setTheme(R.style.AppTheme_NoActionBar);
rootView=inflater.inflate(R.layout.recepie_viewpager, container, false);
//getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
toolbar=(Toolbar)rootView.findViewById(R.id.toolbar_yash);
// ((AppCompatActivity) getActivity()).findViewById(R.id.toolbar_yash).animate().translationY(-(R.id.toolbar_yash).getBottom()).setInterpolator(new AccelerateInterpolator()).start();
viewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
setRetainInstance(true);
viewPager.setOffscreenPageLimit(3);
tabLayout = (TabLayout)rootView. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
//actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
private int previousState, currentState;
#Override
public void onPageScrollStateChanged(int state) {
int currentPage = viewPager.getCurrentItem(); //ViewPager Type
if (currentPage == 2 || currentPage == 0) {
previousState = currentState;
currentState = state;
if (previousState == 1 && currentState == 0) {
viewPager.setCurrentItem(currentPage == 0 ? 2 : 0);
}
}
}
});
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());//(getActivity().getSupportFragmentManager());
adapter.addFrag(new Main_Course(), "");
adapter.addFrag(new Cakes(), "");
adapter.addFrag(new Specials(), "");
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);
}
}
}
And this the xml file i am using :
tools:context=".activity.activity.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appbarmain"
android:theme="#style/AppTheme.NoActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_yash"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar" />
</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>
Below type of visualisation is created when I'm trying to hide the toolbar/actionbar in recepies fragment. What I want is whenever I move into products or swadeshi fragment I get this action bar but when in recepie fragment my actionbar hides and screen consists of my viewpager of 3 elements as shown of cake but instead a blank is created.
Related
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 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?
I have used fragments for drawer item, each fragments consists of non-fixed tabs.I'm using PagerSlidingTabStrip library for showing tabs.When fragment is initialized it shows 1st ViewPager, which is correct but when I click on 2nd tab it shows up 3rd ViewPager.Likewise the last ViewPager is never shown.
Tab xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:textColor="#000000"
android:textSize="#dimen/sp_fifteen"
app:pstsDividerColor="#color/red"
app:pstsIndicatorColor="#color/black"
app:pstsTextAllCaps="true"
app:pstsUnderlineColor="#color/gray" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Adapter class:
private PagerSlidingTabStrip tabStrip;
private Adapter adapter;
public static TowerOneTabs newInstance() {
TowerOneTabs fragment = new TowerOneTabs();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mView = getActivity().getLayoutInflater().inflate(R.layout.tower_tabs_layout, null);
super.onCreate(savedInstanceState);
ViewPager viewPager = (ViewPager) mView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabStrip = (PagerSlidingTabStrip) mView.findViewById(R.id.tabs);
tabStrip.setViewPager(viewPager);
tabStrip.setOnPageChangeListener(this);
return mView;
}
#Override
public void onResume() {
super.onResume();
tabStrip.setOnPageChangeListener(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
private void setupViewPager(ViewPager viewPager) {
//Here we have to pass ChildFragmentManager instead of FragmentManager.
adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(TowerOne.newInstance(), getResources().getString(R.string.tower1));
adapter.addFragment(T11.newInstance(), Constants.KEY_T1_1);
adapter.addFragment(T12.newInstance(), Constants.KEY_T1_2);
adapter.addFragment(T13.newInstance(), Constants.KEY_T1_3);
adapter.addFragment(T14.newInstance(), Constants.KEY_T1_4);
adapter.addFragment(T15.newInstance(), Constants.KEY_T1_5);
viewPager.setAdapter(adapter);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
// BaseActivity.getTitleView().setText(Constants.KEY_TOWER_ONE);
break;
case 1:
mCallback.showDialog();
break;
case 2:
mCallback.showDialog();
break;
case 3:
mCallback.showDialog();
break;
case 4:
mCallback.showDialog();
break;
case 5:
mCallback.showDialog();
break;
default:
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(android.support.v4.app.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);
}
}
I checked this code and its working. If you want to add extra parameter (like Constant), you can edit the SampleFragmentPagerAdapter's addFragment method.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
//viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
setupViewPager(viewPager);
// Give the PagerSlidingTabStrip the ViewPager
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
SampleFragmentPagerAdapter adapter = new SampleFragmentPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
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;
}
}
I am having trouble showing my new fragment . Basically what i doing is i have a viewpager having 3 pages , in the second page i m hiding the current fragment and adding a new one. Everything goes perfectly except that i can't see my new fragment.
My Mainactivity.java
public class MainActivity extends AppCompatActivity {
ViewPager viewPager = null;
NavigationDrawerFragement drawerFragement;
Bitmap image = null;
int notificationExtra = 0;
int nid=0;
Toolbar toolbar;
private void startGetLocationService() {
Intent i = new Intent(this, GetUserLocationService.class);
startService(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_register);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
drawerFragement = (NavigationDrawerFragement) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragement.setUp((DrawerLayout) findViewById(R.id.drawer_layout),toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
//getSupportActionBar().setIcon(R.drawable.account);
getSupportActionBar().setTitle("Eventyze");
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
fragment = new ReminderFragment();
if (i == 1)
fragment = new EventFragment();
if (i == 2)
fragment = new InvitationFragment();
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0)
return "Reminders";
if (position == 1)
return "Events";
if (position == 2)
return "Invitations";
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
#Override
protected void onResume() {
super.onResume();
if(notificationExtra==1){
viewPager.setCurrentItem(2);
}
}
}
the onclick in my 2nd page .
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
InvitedEventsFragment fragment2 = new InvitedEventsFragment();
fragmentTransaction2.hide(EventFragment.this);
fragmentTransaction2.add(R.id.viewpager, fragment2);
fragmentTransaction2.commit();
My InvitedEventsFragment.java
public class InvitedEventsFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_invited_events_fragment, container, false);
}
return view;
} }
My activity_invited_events_fragment.xml
<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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black">
<Button
android:id="#+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/appbarcol2"
android:text="New Fragment"
android:textAllCaps="true"
android:textColor="#android:color/white"
android:textStyle="bold" /> </LinearLayout>
Can someone tell me why it doesn't show anything i the new fragment.
If you're using a ViewPager, the adapter should manage the Fragments.
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import java.util.List;
public class ExampleAdapter extends FragmentPagerAdapter
{
List<Fragment> fragmentList;
public ExampleAdapter(FragmentManager fm, List<Fragment> fragmentList)
{
super(fm);
this.fragmentList = fragmentList;
}
#Override public Fragment getItem(int position)
{
return fragmentList.get(position);
}
#Override public int getCount()
{
return fragmentList.size();
}
public void removeItem(int position, ViewPager pager)
{
pager.setAdapter(null);
this.fragmentList.remove(position);
pager.setAdapter(this);
}
}