I have two fragment in one activity, and I need to know how to just hide the second fragment and leave the firs one
So, i want to hide PerfilDatosFragmen();, but i also need to keep "2" in return statement. how can i do that?
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
String[] encabezado = {"Tarjeta", "Datos"};
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new PerfilTarjetaFragment();
case 1:
return new PerfilDatosFragmen();
}
return null;
}
#Override
public int getCount() {
System.out.println(vacio);
// int vacio = getIntent().getExtras().getInt("AcompaƱante");
/* if(vacio.equals("1")){
a= 1;
}else{
a= 2;
}*/
return 2;
}
It's very simple. PagerAdapter.getCount() is defined the count of your fragments. You always return 2. The best solution is:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
fragments.add(new PerfilTarjetaFragment());
fragments.add(new PerfilDatosFragmen());
}
String[] encabezado = {"Tarjeta", "Datos"};
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
Related
I have ViewPager that has 3 tabs. Tab(3), beside stock fragment, includes 2 more fragments (B) --> (C).
Tab(1)
Tab(2)
Tab(3) --> (B) --> (C)
By pressing a button in (C) I want to refresh/recreate Tab(2).
What's the best way to do it? Thank you.
public class ViewPageAdapter extends FragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
private FragmentManager mFragmentManager;
private Context mContext;
public ViewPageAdapter(#NonNull FragmentManager fm, Context context) {
super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mFragmentManager = fm;
mContext = context;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new FragmentInsta();
case 1: return new FragmentListUnlogged();
case 2: return new FragmentHostUnlogged();
default:
return new FragmentListLogged();
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
Thanks to user named "Andrew" I found the solution.
I override the onPause method in this way.
#Override
public void onResume() {
if(preferenceUtils.getBoolean("isLogged")){
FragmentTransaction trans = getChildFragmentManager().beginTransaction();
trans.replace(R.id.listUnlogged_container, new FragmentListLogged(), "ListUnlogged-ListLogged");
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(FRAGMENT_TAG);
trans.commit();
}
super.onResume();
}
I'm showing fragments in viewpager, and each fragment contains data connection.
I don't want to do something, before selected fragment is shown.
How can I do?
I mean, I don't want to initiate fragments when the activity calls oncreate.(because there's data connection, and I don't want it)
I just want to initiate each fragment, when fragment is selected.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id.view_pager);
List<Fragment> listFragments = new ArrayList<>();
listFragments.add(new Fg_1());
listFragments.add(new Fg_2());
listFragments.add(new Fg_3());
listFragments.add(new Fg_4());
listFragments.add(new Fg_5());
listFragments.add(new Fg_6());
a_pagerAdapter = new A_PagerAdapter(getSupportFragmentManager(), listFragments);
viewPager.setAdapter(a_pagerAdapter);
viewPager.addOnPageChangeListener(this);
}
Instead of creating all of your fragments in your activity onCreate, have your viewPager create them when requested, so for a simple example:
in your implementation of A_PagerAdapter, override getCount() and getItem(int) to be something like:
public class A_PagerAdapter extends FragmentPagerAdapter {
...
private final static int NUM_PAGES = 6;
private final Fragment[] listFragment = new Fragment[NUM_PAGES];
...
public int getCount() {
return NUM_PAGES;
}
...
public Fragment getItem(int index) {
Fragment itemFragment = null;
if (listFragment[index] == null) {
// Hard-coded class factory.. yuck.
switch(index) {
case 0:
itemFragment = new Fg_1();
break;
case 1:
itemFragment = new Fg_2();
break;
case 2:
itemFragment = new Fg_3();
break;
case 3:
itemFragment = new Fg_4();
break;
case 4:
itemFragment = new Fg_5();
break;
case 5:
itemFragment = new Fg_6();
break;
}
// Save this instance in case it is asked for again later..
listFragment[index] = itemFragment;
} else {
// get the fragment we created earlier to avoid re-initializing
itemFragment = listFragment[index];
}
return itemFragment;
}
...
This is a fairly simple/horrible implementation.. in reality it sounds more like you need a caching/lazy loading strategy, possibly triggered in the onResume of the fragments in your view pager..
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {
final int PAGE_COUNT = 5;
private String tabTitles[] = new String[] { "Chats", "Groups", "Contacts","Profile" ,"Settings"};
public SampleFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public Fragment getItem(int position) {
// return PageFragment.create(position + 1);
switch (position) {
case 0:
ChatScreenActivity chatScreenActivity = new ChatScreenActivity();
return chatScreenActivity;
case 1:
GroupChatActivity groupChatActivity = new GroupChatActivity();
return groupChatActivity;
case 2:
ContactsActivity contactsActivity = new ContactsActivity();
return contactsActivity;
case 3:
ProfileActivity profileActivity= new ProfileActivity();
return profileActivity;
case 4:
SettingActivity settingActivity = new SettingActivity();
return settingActivity;
default:
return null;
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}*use this code and do setadapter for your viewpager*
}
I have activity where I have created a viewpager that contains two fragments. I need to get a reference to the existing fragment or it's view, in the activity to refresh the list from the fragment if necessary. I was looking for a solution for two days, but found nothing on this occasion.
So here is my adapter
public class SearchPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public SearchPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if(position == 0)
{
FragmentAyahSearch tab1 = new FragmentAyahSearch();
return tab1;
}
else
{
FragmentSurahList tab2 = new FragmentSurahList();
return tab2;
}
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
below, I create a viewpager and adapter in MainActivity
searchAdapter = new SearchPagerAdapter(getSupportFragmentManager(), searchTitles, Numboftabs);
pager.setAdapter(searchAdapter);
tabs.setViewPager(pager);
I hope you will help me, because I'm losing my mind over this.
I would suggest maintain a list like
private List<Fragment> frag = new ArrayList<Fragment>();
then
public class SearchPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public SearchPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = frag.get(position);
if(fragment == null )
{
if (position == 0)
{
fragment = new FragmentAyahSearch();
}
else
{
fragment = new FragmentSurahList();
}
}
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return frag.size();
}
now if you want the reference of any fragment
just call , frag.get(<position>) will return you desire frgament
//SampleTabsWithIcons.java
public class SampleTabsWithIcons extends FragmentActivity {
private static final int[] ICONS = new int[] {
R.drawable.events,
R.drawable.rss,
R.drawable.user,
R.drawable.bell,
R.drawable.search
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.simple_tabs);
FragmentPagerAdapter adapter = new GoogleMusicAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
}
class GoogleMusicAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(ICONS[position % ICONS.length]);
}
#Override public int getIconResId(int index) {
return ICONS[index];
}
#Override
public int getCount() {
return ICONS.length;
}
}
}
//TestFragment.java
public final class TestFragment extends Fragment {
private static final String KEY_CONTENT = "TestFragment:Content";
public static TestFragment newInstance(int icons) {
TestFragment fragment = new TestFragment();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 20; i++) {
builder.append(icons).append(" ");
}
builder.deleteCharAt(builder.length() - 1);
fragment.mContent = builder.toString();
return fragment;
}
private String mContent = "???";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
}
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView text = new TextView(getActivity());
text.setGravity(Gravity.CENTER);
text.setText(mContent);
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(text);
return layout;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_CONTENT, mContent);
}
}
//TestFragmentAdapter.java
class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
private static final int[] ICONS = new int[] {
R.drawable.events,
R.drawable.rss,
R.drawable.user,
R.drawable.bell,
R.drawable.search
};
private int mCount = ICONS.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(ICONS[position % ICONS.length]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
and my output is,
My question is instead of displaying numbers while selecting each tabs, I want to go to new fragment activity (ie, newpage.java). Now some numbers are showing on each tab selection. How can i implement this.
I have 5 class (first.java,second.java,third.java,four.java,five.java) and 5 layout for each tabs (first.xml... respectively)
I tried a lot but no success. Does anyone know the answer.
Thanks.
Ok you can make your own Fragments and then return them in the getItem(int position); for example, you could have an array of your Fragments calendar, feed, etc. then on each position you return one.
//SampleTabsWithIcons.java
Fragment[] tabFragments = new Fragment[] {CalendarFragment.newInstance(),
FeedFragment.newInstance()}
.....
#Override
public Fragment getItem(int position) {
return tabFragments[position];
}
You can simply use this and set the tab to the viewPager ...
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
Inside fragment pager adapter you can do like this.
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
frag = UsageRecoSummaryFragemrent.newInstance(position);
// changeColor(newColor);
break;
Inside fragment
public static UsageRecoSummaryFragemrent newInstance(int position) {
UsageRecoSummaryFragemrent f = new UsageRecoSummaryFragemrent();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, 0);
f.setArguments(b);
return f;
}
I've written this class that extends FragmentStatePagerAdapter in order to swipe between views. Now I need to make the swiping list circular so that swiping after the last fragment would display the first fragment. I haven't found a way to properly do that, any help?
Here's the code of the adapter:
public class DetailsPagerAdapter extends FragmentStatePagerAdapter {
List<Detail> details=null;
public DetailsPagerAdapter(FragmentManager supportFragmentManager, List<Detail> details) {
super(supportFragmentManager);
this.details=details;
}
#Override
public Fragment getItem(int i) {
System.out.println("Fetching item at position "+i);
Fragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putString("img",details.get(i).getImageFileName());
args.putString("desc",details.get(i).getDescription());
fragment.setArguments(args);
return fragment;
}
public int getCount() {
return details.size();
}
}
in your Adapter, try something like that
#Override
public Fragment getItem(int pos) {
pos = pos % details.size();
....
}
#Override
public int getCount() {
return 99999;
}