Kill thread on change fragments - java

I have an activity with 4 Fragments and in each fragment I have a thread the 4 fragments are started together but I need to slide between them so that each one is visible, what I would like to know is how can I leave only the thread of the fragment that is being viewed and Interrupt the others, when you slide to the other fragments the same thing starts a thread and interrupts the others
Adapter
public TabManualAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0 :
fragment = new Fragment1();
break;
case 1 :
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
}
return fragment;
}
#Override
public int getCount() {
return tituloTabsManual.length;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tituloTabsManual[position];
}
}
Host Activity :
viewPager.setPageTransformer(true,new ZoomOutPageTransformer());
viewPager.setOffscreenPageLimit(4);
slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this,R.color.colorPrimary));
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setBackgroundColor( ContextCompat.getColor( this, R.color.black ) );
TabManualAdapter tabManualAdapter = new TabManualAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabManualAdapter);

Related

Multiple Tabs with FragmentStatePageAdapter and ViewPager

Good Afternoon, I have an activity that contains 4 Fragments using tab layout, when I initialize the Activity only two fragments are initialized at a time, for example while I am in the first fragment, Fragment 1 and 2 are initialized, when I slide to 2 it initializes the third and then 2 and 3 are initialized and the first is destroyed, is it possible for everyone to be initialized together?
this is my Adapter:
public class TabManualAdapter extends FragmentStatePagerAdapter {
private String[] tituloTabsManual = {"TAB1","TAB2","TAB3","TAB4"};
public TabManualAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0 :
fragment = new Fragment1();
break;
case 1 :
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
}
return fragment;
}
#Override
public int getCount() {
return tituloTabsManual.length;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tituloTabsManual[position];
}
}
and Activity Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual);
SlidingTabLayout slidingTabLayout = findViewById(R.id.stl_tabs_manual);
viewPager = findViewById(R.id.vp_pagina_manual);
viewPager.setPageTransformer(true,new ZoomOutPageTransformer());
slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this,R.color.colorPrimary));
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setBackgroundColor( ContextCompat.getColor( this, R.color.black ) );
TabManualAdapter tabManualAdapter = new TabManualAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabManualAdapter);
CircleIndicator indicator = findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
slidingTabLayout.setViewPager(viewPager);

IndexOutOfBoundsException when selecting tab in Tablayout

I get IndexOutOfBoundsException error when i want selecting the tab in the TabLayout :
This is the initTablayout function , that called in the onCreate method:
//======================================== Init Tablayout and view pager
private void initTabLayout() {
mainActivityViewPager = (ViewPager) findViewById(R.id.view_pager_main_activity);
mainActivityTabLayout = (TabLayout)findViewById(R.id.tab_layout_main_activity);
TabLayout.Tab tab = mainActivityTabLayout.getTabAt(1);
tab.select();
FragmentManager manager = getSupportFragmentManager();
MainActivityPagerAdapter adapter = new MainActivityPagerAdapter(manager);
mainActivityViewPager.setAdapter(adapter);
mainActivityTabLayout.setupWithViewPager(mainActivityViewPager);
mainActivityViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mainActivityTabLayout));
mainActivityTabLayout.setTabsFromPagerAdapter(adapter);
}
I got this error where i choose index of selected tab on the getTabAt(1) method , i have three tab on the PagerAdapter class :
public class MainActivityPagerAdapter extends FragmentStatePagerAdapter {
//============================================ Constructor
public MainActivityPagerAdapter(FragmentManager fm) {
super(fm);
}
//============================================ GetItem Method ()
#Override
public Fragment getItem(int position) {
Fragment frag = null;
switch (position) {
case 0:
frag = new Fragment_one();
break;
case 1:
frag = new Fragment_two();
break;
case 2:
frag = new Fragment_three();
break;
}
return frag;
}
//============================================= GetCount Method ()
#Override
public int getCount() {
return 3;
}
//============================================= GetPageTitle
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "اول ";
break;
case 1:
title = "دوم ";
break;
case 2:
title = "سوم ";
break;
}
return title;
}
}
Complete error is :
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
It seem like you forget to addTab to your mainActivityTabLayout so your TabLayout will have 0 item. Therefore, you got IndexOutOfBoundsException when you access to tab1
mainActivityTabLayout.addTab(tabLayout.newTab().setText("1"));
mainActivityTabLayout.addTab(tabLayout.newTab().setText("2"));
mainActivityTabLayout.addTab(tabLayout.newTab().setText("3"));
Select tab3
Do following :
mainActivityTabLayout.addTab(tabLayout.newTab().setText("3"),true);

Not calling before fragment is shown

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*
}

while replacing the fragment view pager the viewpager fragment shows blank

I am calling the view pager fragments by replacing over frame layout but when when i call it again the last loaded fragments of view pager are shown blank.
//Here I am replacing the view pager fragment in main activity
All_Women_Categories fragment = new All_Women_Categories();
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
//Here is my called view pager fragment
public class All_Ethnic_Fragment extends Fragment {
private static SectionsPagerAdapter mSectionsPagerAdapter;
private static ViewPager mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.all_women_ethnic_view_pager,
container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.women_ethnic_pager);
mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity()
.getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
return rootView;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Sarees.newInstance("Hello");
case 1:
return Lehengas.newInstance("Hello");
case 2:
return Salwars_n_Churidars.newInstance("Hello");
case 3:
return Kurtis.newInstance("Hello");
case 4:
return Dress_Materials.newInstance("Hello");
case 5:
return Stitched_Suits.newInstance("Hello");
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.sarees).toUpperCase();
case 1:
return getString(R.string.lehngas).toUpperCase();
case 2:
return getString(R.string.salwars).toUpperCase();
case 3:
return getString(R.string.kurti).toUpperCase();
case 4:
return getString(R.string.dress_material).toUpperCase();
case 5:
return getString(R.string.stiched).toUpperCase();
}
return null;
}
}
}
If anyone get anything that what's happening then please tell me..
Thanks..
I'm not sure I got your question, but I think you should stack fragments instead of replacing them. Instead of
.replace(R.id.frame_container, fragment).commit();
You should try using add(Fragment fragment), remove() and/or show(Fragment fragment). In this way, you may add all of your fragments first, and then decide to show/hide them as appropriate.

Change content of fragment in FragmentPagerAdapter by ActionBar button click

I have app with FragmentStatePagerAdapter. One of the fragment contains some linearlayouts. I also have ActionBar. When i click at icon(button) on ActionBar, I will update my ArrayList with strings. After update ArrayList i want to update LinearLayout in fragment.
This is my Java code of FragmentPagerAdapter:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter{
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position) {
case 0: {
Fragment fragment = new NejblizsiBary();
Bundle args = new Bundle();
args.putInt(NejblizsiBary.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
case 1: {
Fragment fragment3 = new Mapa();
Bundle args = new Bundle();
args.putInt(Mapa.ARG_SECTION_NUMBER, position + 2);
fragment3.setArguments(args);
return fragment3;
}
case 2: {
Fragment fragment2 = new OblibeneBary();
Bundle args = new Bundle();
args.putInt(OblibeneBary.ARG_SECTION_NUMBER, position + 3);
fragment2.setArguments(args);
return fragment2;
}
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section3).toUpperCase(l);
case 2:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
Here is my class with creating content of Fragment:
public class NejblizsiBary extends Fragment implements LocationListener {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public NejblizsiBary() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
LinearLayout mainLayout = (LinearLayout) rootView.findViewById(R.id.hl);
getApplicationContext();
LayoutInflater inflater_layout = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for(int i = 0; i < pocet_baru;i++){
View itemBox = inflater_layout.inflate(R.layout.jedenbar,null);
itemBox.setId(i);
TextView nazev = (TextView)itemBox.findViewById(R.id.nazev);
nazev.setText(bary.get(i).getNazev());
View.OnClickListener handler = new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Detaily dialog = new Detaily();
Bundle args = new Bundle();
int id = arg0.getId();
args.putDouble("hlat", mLatitude);
args.putDouble("hlong", mLongitude);
args.putDouble("lat", bary.get(id).getLatitude());
args.putDouble("long", bary.get(id).getLongtitude());
args.putString("nazev", bary.get(id).getNazev());
args.putString("adresa", bary.get(id).getAdresa());
args.putString("mesto", bary.get(id).getMesto());
args.putString("popis", bary.get(id).getPopis());
dialog.setArguments(args);
dialog.show(getActivity().getFragmentManager(), "MyDialog");
}
};
itemBox.setOnClickListener(handler);
mainLayout.addView(itemBox);
}
return rootView;
}
Can U help me with my problem pls?
Simplest and most straight forward way is to register each fragment on its activity while creating it. Then delegate event made by actionbar button through the activity to appropriate fragment.
Other way is to use some kind event distribution observer pattern or event-bus patter.
I use event-bus implemented by RoboGuice personaly. Other implementations could be found in Guava or Otto libraries.

Categories

Resources