I'm using an awesome library : Alerter. I have 3 fragments inside a ViewPager. When I display a fragment, I want to display an Alert with this library. However, the alert is not showing up the first time. When I click on a button to display a new one, the first one shuws and juste after the second one. Just like the alert was delayed until a new one is requested.
Here is the ocde I use for the Main Fragment :
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
final MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle) adapter.getItem(position);
fragmentToShow.onResumeFragment();
}
});
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Cube", "Osselet", "Watch"};
private MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
// Return Map Fragment
if (position == 0) {
return new RecordCubeFragment();
}
//Return Toilet List Fragment
else if (position == 1) {
return new RecordOsseletFragment();
}
else if (position == 2) {
return new RecordWatchFragment();
}
else {
return new RecordCubeFragment();
}
}
And there is the code of a child fragment in the ViewPager :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG, "call oncreateview");
View v = inflater.inflate(R.layout.fragment_record_cube, container, false);
lectureButton = (ImageButton) v.findViewById(R.id.lectureButton);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Log.d(TAG, "call onview created");
super.onViewCreated(view, savedInstanceState);
lectureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Alerter.create(getActivity())
.setTitle("Warning !")
.setText("second alert.")
.setIcon(R.drawable.alert_icon)
.setBackgroundColorInt(Color.RED)
.setDuration(2000)
.show();
}
});
Alerter.create(getActivity())
.setTitle("Warning !")
.setText("first alert.")
.setIcon(R.drawable.alert_icon)
.setBackgroundColorInt(Color.RED)
.setDuration(2000)
.show();
}
Thx for the help, I know that lifeCycle of fragments is different in ViewPager, this is why I implemented an OnPageChangeListener but I cannot get rid of this problem.
Related
I am trying to fill Tablayout from 2 different fragments depending on the value (0 or 1) of the argument Radios.newInstance(int type)
The first fragment contains all radio stations and the second contains the favorite stations
But it shows me always the fragment containing the favorite stations
public class HomeFragment extends Fragment {
public static final String TAG = "HomeFragment";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ProgressBar mProgressView;
private ViewGroup mContainer;
private BaseActivity activity;
public HomeFragment() {
}
public static HomeFragment newInstance() {
return new HomeFragment();
}
public void showProgress(final boolean show) {
mContainer.setVisibility(show ? View.GONE : View.VISIBLE);
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
activity = (BaseActivity) getActivity();
activity.findViewById(R.id.tabs).setVisibility(View.VISIBLE);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
activity.getSupportActionBar().show();
mProgressView = (ProgressBar) activity.findViewById(R.id.progress);
mContainer = container;
showProgress(true);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.container);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(RadiosFragment.newInstance(0));
fragments.add(RadiosFragment.newInstance(1));
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(), fragments);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) activity.findViewById(R.id.tabs);
tabLayout.setVisibility(View.VISIBLE);
tabLayout.setTabMode(TabLayout.GRAVITY_CENTER);
tabLayout.setupWithViewPager(mViewPager);
showProgress(false);
return view;
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "RADIOS";
case 1:
return "FAVORITES";
default:
return null;
}
}
}
}
This is the fragment that i want to show, if type == 0 it shows the all radio stations, and if type == 1 it shows the favorite stations
public class RadiosFragment extends Fragment {
private static String TYPE = "NONE";
private FirebaseRecyclerAdapter<FireBaseManager.Radio, ViewHolder> mAdapter = null;
private FirebaseRecyclerAdapter<FireBaseManager.Favorites, ViewHolder> mAdapter_fav = null;
private RecyclerView recyclerView;
public ArrayList<FireBaseManager.Favorites> listOrder;
public RadiosFragment() { }
public static RadiosFragment newInstance(int type) {
if (type == 1 )
TYPE = "favorite";
else
TYPE = "radios";
RadiosFragment fragment = new RadiosFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
final Context context = view.getContext();
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
Query query = FireBaseManager.Radio.Ref.orderByChild(FireBaseManager.Radio.Table.Name.text);
ProgressDialog progressDialog = new ProgressDialog(getContext());
if (TYPE == "favorite"){
....
#Override
protected void populateViewHolder(ViewHolder viewHolder, FireBaseManager.Favorites model, int position) {
...
viewHolder.Initialize(Data);
...
}
};
recyclerView.setAdapter(mAdapter_fav);
}
});
}
else if(TYPE == "radios") {
....
#Override
protected void populateViewHolder(ViewHolder viewHolder, FireBaseManager.Radio model, int position) {
...
viewHolder.Initialize(Data);
...
});
}
};
recyclerView.setAdapter(mAdapter);
});
}
return view;
}
}
I think the problem has to do with onCreateView / onCreate but i am no sure, can you help me please.
This might help you.
mViewPager.setCurrentItem(0);
Add this line after you setup tabLayout with viewpager
thank you very much for your answers, i have found a solution for my problem.
the solution is to add Listener on the Tablayout and intercept the events.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0)
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.flContent, RadiosFragment.newInstance(0), FavoriteActivity.TAG).addToBackStack(null).commit();
if (tab.getPosition() == 1)
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.flContent, RadiosFragment.newInstance(1), FavoriteActivity.TAG).addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
I am able to get DFragment on top of AFragment and on press back of DFragment I am getting AFragment. But the problem that I am facing is when AFragment is shown,BFragment and CFragment show their respective layouts. But when I traverse from A to D, then B and C show D's layouts only.
I have tried notifyDataSetChanged on the Adapter but still doesn't work properly. Please help
My MainActivity
public class MainActivity extends FragmentActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence tabTitles[] = {"A", "B", "C"};
int numTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), tabTitles, numTabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
}
}
This is my ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence tabTitles[];
int numTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence tabTitles[], int numTabs) {
super(fm);
this.tabTitles = tabTitles;
this.numTabs = numTabs;
}
#Override
public Fragment getItem(int position) {
if(position==0)
return new AFragment();
else
if(position==1)
return new BFragment();
else
return new CFragment();
}
#Override
public int getCount() {
return numTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
This is my 0th fragment
public class AFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View rootView =inflater.inflate(R.layout.a,container,false);
Button b = (Button)rootView.findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity) context).getSupportFragmentManager().beginTransaction().add(R.id.container, new DFragment())
.addToBackStack("").commit();
}
});
return rootView;
}
}
This is the new fragment that comes on top of my 0th fragment
public class DFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_d,null);
return rootView;
}
}
I have an activity and pager adapter in it which displays 3 fragments. The fragments are shuffled. I need to know the number of each page when I am swiping through them and that number needs to be displayed in a textView. For example, when I am in the first page number 1 is displayed, second page - number 2 and so on.
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int arg0) {
return this.fragments.get(arg0);
}
#Override
public int getCount() {
return this.fragments.size();
}
public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
}
mainActivity.java
public class testActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager_adapter);
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you want to be displaying the number in your fragment, use this
In your Activity
#Override
public Fragment getItem(int position) {
// Here you can add an argument that will be passed to the fragment
// In your case you need to pass the page number
Fragment fragment = this.fragments.get(arg0);
Bundle b = new Bundle();
b.putInt("page_number", position);
fragment.setArguments(b);
return fragment;
}
In you fragment do this
int number;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read the data that Activity passed to us
if (savedInstanceState == null) {
Bundle args = getArguments();
if (args != null) {
number = args.getInt("page_number") + 1;
}
}
else {
number = savedInstanceState.getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Here you need to find your TextView and show the number
View v = inflater.inflate(R.layout.some_layout, container, false);
((TextView) v.findViewById(R.id.someTextView)).setText(String.format("%d", number));
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("page_number", number);
}
If you want to be displaying the number in your Activity, use this
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
// !!! Change ME!!!!!
textView = (TextView) findViewById(R.id.someTextView);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
textView.setText("Position: " + i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
pager.setAdapter(mPagerAdapter);
}
Use PageChangeListener as:
yourPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
yourTextView.setText("Page: " + position);
}
... ...
});
I am facing the very weird problem,i found the similar kind of problem over the net but none of the solution helps me to get rid of this.
Problem ::
I am having a one fragment which have 3 tabs,(tabs created using fragment tab host).Now every tabs have different fragment.
From first tab,i have set one fragment where i have used view pager and circle page indicator to display the images with dots(circle).
Now when i swipe the image from 1st to 2nd then 3rd and so on,it works fine.
But after reaching on image 2nd,when i click on tab2 and again came back to tab1,my images lost.
Your guidance or any help/links will be appreciated..
Many many thanks in advance.
For your understanding here i am posting code below ::
FragmentwithTabHost ::
public class FragmentwithTabHost extends Fragment{
private View rootView;
private FragmentTabHost mTabHost;
private Context mContext;
public FragmentwithTabHost() {
}
public FragmentwithTabHost(Context ctx) {
mContext=getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.mycardswithtabs, container,
false);
mTabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), android.R.id.tabcontent);
mTabHost.setBackground(getActivity().getResources().getDrawable(R.drawable.normal));
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("tab1", null),
Fragment1.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("tab2", null),
Fragment2.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("tab3", null),
Fragment3.class, null);
return rootView;
}
}
Fragment1 ::
public class Fragment1 extends Fragment{
// private Context mContext;
private View rootView;
SlidesFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
LinearLayout llSponseredImage,llSponserdByText;
ImageView imgsponser1,imgsponser2,imgsponser3,imgsponser4;
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.my_card, container,false);
mAdapter = new SlidesFragmentAdapter(getActivity()
.getSupportFragmentManager());
llSponseredImage=(LinearLayout)rootView.findViewById(R.id.mycardbottomViewSponseredImage);
llSponserdByText=(LinearLayout)rootView.findViewById(R.id.mycardbottomsponsredby);
imgsponser1=(ImageView)rootView.findViewById(R.id.imgsponser1);
imgsponser2=(ImageView)rootView.findViewById(R.id.imgsponser2);
imgsponser3=(ImageView)rootView.findViewById(R.id.imgsponser3);
imgsponser4=(ImageView)rootView.findViewById(R.id.imgsponser4);
mPager = (ViewPager) rootView.findViewById(R.id.pager);
mPager.setOffscreenPageLimit(4);
mPager.setClipToPadding(false);
mPager.setPageMargin(12);
mPager.setAdapter(mAdapter);
mIndicator = (CirclePageIndicator) rootView.findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
((CirclePageIndicator) mIndicator).setSnap(true);
mPager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("3242353652523");
MyCardsWithOffersFragment myCardsWithOffersFragment=new MyCardsWithOffersFragment();
}
});
mIndicator
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
/*Toast.makeText(getActivity(),
"Changed to page " + position,
Toast.LENGTH_SHORT).show();*/
if(position==0 || position==2){
llSponseredImage.setVisibility(View.GONE);
llSponserdByText.setVisibility(View.GONE);
}else if(position==1){
llSponseredImage.setVisibility(View.VISIBLE);
llSponserdByText.setVisibility(View.VISIBLE);
imgsponser1.setImageResource(R.drawable.sponser1);
imgsponser2.setImageResource(R.drawable.sponser2);
imgsponser3.setImageResource(R.drawable.sponser3);
imgsponser4.setImageResource(R.drawable.sponser4);
}else if(position==3){
llSponseredImage.setVisibility(View.VISIBLE);
llSponserdByText.setVisibility(View.VISIBLE);
imgsponser1.setImageResource(R.drawable.sponser5);
imgsponser2.setImageResource(R.drawable.sponser6);
imgsponser3.setImageResource(R.drawable.sponser7);
imgsponser4.setImageResource(R.drawable.sponser8);
}
}
#Override
public void onPageScrolled(int position,
float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return rootView;
}
public class SlidesFragmentAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter {
private int[] Images = new int[] { R.drawable.first_image, R.drawable.second_image,
R.drawable.third_image, R.drawable.four_image
};
private int[] ICONS = new int[] { R.drawable.first_image, R.drawable.second_image,
R.drawable.third_image, R.drawable.four_image };
private int mCount = Images.length;
public SlidesFragmentAdapter(android.support.v4.app.FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
return new DemoFragment(Images[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public float GetPageWidth (int position) {
return 0.93f;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
}
I think this can be achieved using show() or add() method. If it is a Activity without Tabhost then its easy. This case while tab switching we have to apply the same logic.
Check this solution
I guess this will give you some idea.
I am using Holoeverywhere and ViewPagerIndicator; using Holoeverywhere1 I implemented the slider and tabs in the Fragment using ViewPagerIndicator. Everything is working fine, Slider working, the menu in it, the tabs; the tabs works fine only the first time, when I move to other Fragment using the slider and come back to the tabs Fragment, the contents are no more available.
Code for the Fragment where tabs are created
public class SeconFrag extends Fragment {
ViewPager mViewPager;
FragmentAdapter mTabsAdapter;
PageIndicator mIndicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTabsAdapter = new FragmentAdapter(getSupportFragmentManager());
View view = inflater.inflate(R.layout.second_frag);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mViewPager.setAdapter(mTabsAdapter);
TitlePageIndicator indicator = (TitlePageIndicator) view
.findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
indicator.setFooterIndicatorStyle(IndicatorStyle.Triangle);
mIndicator = indicator;
return view;
}
#Override
public void onResume() {
super.onResume();
getSupportActionBar().setSubtitle("Create");
}
}
FragmentAdapter code
public class FragmentAdapter extends FragmentPagerAdapter{
protected static final String[] CONTENT = new String[] { "Choose", "Customise" };
private int mCount = CONTENT.length;
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return TabOne.newInstance();
} else if (position == 1) {
return TabTwo.newInstance();
}else if (position == 3 ) {
return TabOne.newInstance();
}else
return null;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return FragmentAdapter.CONTENT[position % CONTENT.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
on of the tab Fragment
public final class TabOne extends Fragment {
public static TabOne newInstance() {
TabOne fragment = new TabOne();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.tab_one, container,
false);
return myFragmentView;
}
}
in the SeconFrag OnPause() I removed the Fragment no luck, hide() it in the OnPause() and tried to show() in the OnResume() still not showing content after the Fragment is changed.
EDIT