i found an example to use fragments without using tabBar
but now i founded that a fragment OnCreatView called on previos fragment and with this i haven't any control to lifecycle of fragment
this is my code
public class AddTextActivity AppCompatActivity {
private PagerAdapter mPagerAdapter;
public static FragmentManager frmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cordinate);
frmanager=getSupportFragmentManager();
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<>();
fragments.add(Fragment.instantiate(this,Frags.Addtext1.class.getName()));
fragments.add(Fragment.instantiate(this,Frags.Addtext2.class.getName()));
fragments.add(Fragment.instantiate(this,Frags.Addtext3.class.getName()));
this.mPagerAdapter = new PagerAdapter1(frmanager, fragments);
ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);
}
and this is the pagerAdapter1
public class PagerAdapter1 extends FragmentPagerAdapter {
private List<Fragment> fragments;
/**
* #param fm
* #param fragments
*/
public PagerAdapter1(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
/* (non-Javadoc)
* #see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
/* (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getCount()
*/
#Override
public int getCount() {
return this.fragments.size();
}
}
so now how can i prevent from calling onCreatView of next fragment ??
For determine which page is selected:
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// TODO insert your code here
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Related
In my app i am using pager adapter to load 2 fragments, the fragments are not getting loaded and view pager remains null. Where i am going wrong? Any help will be appreciated
Here is my code
I am setting this adapter to my view pager from activity
public class ViewPagerActivityAdapter extends PagerAdapter {
ArrayList<Fragment> tablist;
public ViewPagerActivityAdapter(ArrayList<Fragment> tablist) {
this.tablist = tablist;
}
#Override
public int getCount() {
return tablist.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
return null;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
}
}
Activity Part
private ViewPagerActivityAdapter viewPagerAdapter;
private ArrayList<Fragment> fragments_faq;
fragments_faq = new ArrayList<>();
FragmentOne frag1 = new FragmentOne();
tablayout.addTab(tablayout.newTab().setText("fragone"));
fragments_faq.add(frag1);
FragmentTwo frag2 = new FragmentTwo();
tablayout.addTab(tablayout.newTab().setText("fragtwo"));
fragments_faq.add(frag2);
private void setPagerAdapter() {
viewPagerAdapter = new ViewPagerActivityAdapter(fragments_faq);
viewpager.setAdapter(viewPagerAdapter);
viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
viewpager.setOffscreenPageLimit(2);
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
for details check this gist
https://gist.github.com/vinay6kr/33359c3f3b0e9f28e33bd383b01e9d9f
if you want to show fragments in viewpager you should use FragmentStatePagerAdapter
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
public MyViewPagerAdapter(FragmentManager fm, CharSequence mTitles[]) {
super(fm);
this.Titles = mTitles;
}
#Override
public Fragment getItem(int position) {
if (position == 0)
return new Fragment1().getInstance();
else if (position == 1)
return new Fragment2().getInstance();
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return Titles.length;
}
}
and to Set them
void setUpTabs() {
String Titles[] = {"Frag1","Frag2"};
MyViewPagerAdapter adapter = new MyViewPagerAdapter(this.getSupportFragmentManager(), Titles);
viewPager.setAdapter(adapter);
}
You can try like adapter look like
class ViewPagerActivityAdapter extends FragmentPagerAdapter {
// fragments to instantiate in the viewpager
private List<Fragment> fragments;
// constructor
public ViewPagerActivityAdapter(FragmentManager fm,List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
// return access to fragment from position, required override
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
// number of fragments in list, required override
#Override
public int getCount() {
return this.fragments.size();
}
}
Add Fragment
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,
FragmentOne.class.getName()));
fragments.add(Fragment.instantiate(this,
FragmentTwo.class.getName()));
Add to view Pager
ViewPagerActivityAdapter mPagerAdapter;
this.mPagerAdapter = new ViewPagerActivityAdapter(
super.getSupportFragmentManager(), fragments);
mPager = (ViewPager) super.findViewById(R.id.pager);
mPager.setAdapter(this.mPagerAdapter);
You should use FragmentPagerAdapter or FragmentStatePagerAdapter for this.Here is sample code.
public class ViewPagerActivityAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> tablist;
public ViewPagerActivityAdapter(ArrayList<Fragment> tablist) {
this.tablist = tablist;
}
#Override
public int getCount() {
return tablist.size();
}
#Override
public Fragment getItem(int position) {
return tablist.get(position);
}
}
I have this "frame" app with toolbar and viewPager.
BaseActivity:
public abstract class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
}
protected abstract int getLayoutResource();
}
ToolbarActivity:
protected static Toolbar toolbar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = findViewById(R.id.flToolbarContentContainer);
if (contentView instanceof ViewGroup) {
((ViewGroup) contentView)
.addView(LayoutInflater.from(this)
.inflate(getToolbarLayoutResource()
, (ViewGroup) contentView, false));
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected int getLayoutResource() {
return R.layout.activity_toolbar;
}
protected abstract int getToolbarLayoutResource();
public void showToolbar() {
toolbar.setVisibility(View.VISIBLE);
}
public void hideToolbar() {
toolbar.setVisibility(View.GONE);
}
public static void setTitle(String title){
toolbar.setTitle(title);
}
}
MainActivity:
public class MainActivity extends ToolbarActivity {
#Override
protected int getToolbarLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabFragment homeFragment = new TabFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.llMainActivityContainer, homeFragment)
.commit();
}
And The. TabFragment:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
private String[] titles = new String[3];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
titles[0] = "Összes";
titles[1] = "Saját";
titles[2] = "Közelben";
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.view_pager,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
ToolbarActivity.setTitle(""+titles[position]);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SecondFragment();
case 2 : return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
My problem is if I open a new activity from the viewPager and finish it,
when I return to the viewPager activity the onPageSelected listener runs but not changing my toolbar title.
Can you help me how can I solve this?
Thank you!
try
getActivity.setTitle(""+titles[position]);
I used a ViewPager with FragmentPagerAdapter in my app. I created 4 fragments. Also I used EventBus library to refresh current fragment's background color. When I changed the page, onEvent method was triggered, then all 4 fragments' background color was changed. But I want to change only current fragment's background color. How can I fix this bug? Sorry for my bad English.
ViewPager as below :
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
MyPageViewActivity as below :
public class PageViewActivity extends FragmentActivity {
MyPagerAdapter pageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragments);
pager.setAdapter(pageAdapter);
pager.setOffscreenPageLimit(4);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
EventBus.getDefault.post(new TriggerEvent(position));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragment.newInstance("1"));
fList.add(MyFragment.newInstance("2"));
fList.add(MyFragment.newInstance("3"));
fList.add(MyFragment.newInstance("4"));
return fList;
}
}
finally MyFragment.class
public class MyFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
RelativeLayout relativeLayout;
String msg;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
msg = getArguments().getString(EXTRA_MESSAGE);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativelayout);
return v;
}
public void onEvent(TriggerEvent trigger) {
relativeLayout.setBackgroundColor(randomColor());
}
}
try this,
public void onEvent(TriggerEvent trigger) {
if(isCurrentFragment){
relativeLayout.setBackgroundColor(randomColor());
}
}
I am doing swiping application in android. But I got one problem that getItem() method
is calling twice initially. I tried to solve this but I didn’t get solution. please help me
to find out solution. below snippets my code:-
public class DisplayEMIBOFQuestionActivity extends FragmentActivity {
private ViewPager pager;
private int savePosition;
private Context context;
private String fragTag1;
private String fragTag2;
/*
* (non-Javadoc)
*
* #see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.common_emi_bof_display_question);
context = getLayoutInflater().getContext();
if(Helper.isTablet)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// Initialise the pager
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
/**
* on swiping the viewpager make respective tab selected
* */
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int position) {}
public void onPageScrolled(int position, float arg1, int arg2) {}
public void onPageScrollStateChanged(int arg0) {
}
});
getPager().setPageTransformer(true, new SwipeAnimation());
}
public ViewPager getPager() {
return pager;
}
public void setPager(ViewPager pager) {
this.pager = pager;
}
public String getFragTag1() {
return fragTag1;
}
public void setFragTag1(String fragTag1) {
this.fragTag1 = fragTag1;
}
public String getFragTag2() {
return fragTag2;
}
public void setFragTag2(String fragTag2) {
this.fragTag2 = fragTag2;
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int pos) {
System.out.println("************** "+pos);
Helper.currentQuestion = pos;
if(Helper.randomQuestionList.get(pos).getSubQuestionType().equals(QuestionType.BOF.toString()))
return new DisplayBOFQuestionFragment();
else
return new DisplayEMIQuestionFragment();
}
#Override
public int getCount() {
return Helper.NUMBEROFQUESTIONS;
}
#Override
public CharSequence getPageTitle(int position) {
return super.getPageTitle(position);
}
}
public void setPagerPosition(int pos){
pager.setCurrentItem(pos);
}
}
It gets one fragment and two adjacent ones (here you just have one), so initially will get Tab1 and Tab2 to get ready when you swipe to Tab2, at Tab2 selected will also call getItem for Tab3 to prepare for swipe.
After the device goes on standby, if I call getSupportFragmentManager() I get a FragmentManager that contains fragments not initialised with all their variables set to null.
Here there is some code:
this.mAdapter = new MyAdapter(getSupportFragmentManager());
this.mPager = (ViewPager) findViewById(R.id.pager);
this.mPager.setAdapter(mAdapter);
TabPageIndicator titleIndicator = (TabPageIndicator) findViewById(R.id.titles);
titleIndicator.setViewPager(mPager);
titleIndicator.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
mAdapter.getItem(position).onFocus();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
});
This is MyAdapter class:
public static class MyAdapter extends FragmentStatePagerAdapter
{
ArrayList<ExtendedFragment> tabs = new ArrayList<ExtendedFragment>();
String[] titles = new String[] { "FRAG1", "FRAG2", "FRAG3", "FRAG4", "FRAG5", "FRAG6"};
public MyAdapter(FragmentManager fm)
{
super(fm);
tabs.add(new frag1());
tabs.add(new frag2());
tabs.add(new frag3());
tabs.add(new frag4());
tabs.add(new frag5());
tabs.add(new frag6());
}
#Override
public int getCount()
{
return tabs.size();
}
#Override
public ExtendedFragment getItem(int position)
{
return tabs.get(position);
}
#Override
public CharSequence getPageTitle(int position)
{
return titles[position];
}
}
The ExtendedFragment implements the method onFocus(), each fragment override that because i need to do some actions when a tab gets the focus. When I resume the device from standby and onFocus() is fired, if I try to get the View using getView() I get null.
Why my view is null?
You could try overriding onSaveInstanceState method.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mContentFragment = getSupportFragmentManager().getFragment(
savedInstanceState, "mContent");
}
if (mContentFragment == null) {
mContentFragment = new YourFragment();
}
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent",
mContentFragment);
}