I have viewpager with tablayout, and have 3 fragment in it. In my fragment 2 and 3 , I have swipe to refresh to update data from firebase database.
I want it refresh with 1 button in toolbar, and refresh all of the fragment inside it.
1 more problem is, i have to swipe refresh 2 times the fragment to update the recyclerview.....
I dont know how to do it, please help
TwoFragment
public static final String TAG = "TWO_FRAGMENT";
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
} else {
mAuth = FirebaseAuth.getInstance();
userRef = FirebaseDatabase.getInstance().getReference("user_course");
users = FirebaseAuth.getInstance().getCurrentUser();
daftarTugasRef = FirebaseDatabase.getInstance().getReference("tugas");
mTugasRef = FirebaseDatabase.getInstance().getReference("tugas_course");
mFlagTugas = FirebaseDatabase.getInstance().getReference("flag_tugas");
LoadData();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
v = inflater.inflate(R.layout.fragment_two, container, false);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
LoadData();
swipeLayout.setRefreshing(false);
listTugas.clear();
}
private void onLoaded() {
swipeLayout.setEnabled(true);
swipeLayout.setRefreshing(false);
}
}, 500);
}
});
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
viewPager.setCurrentItem(position);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
reloadFragment("TWO_FRAGMENT");
setupTabIcons();
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
viewPager.getAdapter().notifyDataSetChanged();
}
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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// viewPager.getAdapter().notifyDataSetChanged();
// adapter.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
protected void reloadFragment(String TAG){
// Reload current fragment
Fragment frg = null;
frg = this.getSupportFragmentManager().findFragmentByTag(TAG);
FragmentTransaction ft =this.getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
You can use EventBus, put this in all your fragments:
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(ViewEvent viewEvent) {
if (viewEvent.getMessage().equals("updateViews")) {
updateView();
}
}
and when you want to update you can send an event like this:
EventBus.getDefault().post(new ViewEvent("updateViews"));
PS: ViewEvent is an object that you must create with what to send to all suscribed fragments.
public class ViewEvent {
private String message;
public ViewEvent( String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Just call the following method on your button click to refresh the Fragments -
protected void reloadFragment(String TAG){
// Reload current fragment
Fragment frg = null;
frg = getActivity().getSupportFragmentManager().findFragmentByTag(TAG);
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
Declare your TAG variable inside the Fragment by the following line of code -
public static final String TAG = "HOME_FRAGMENT";
and whenever you are pushing the Fragment in your activity kindly use the same TAG like this -
getSupportFragmentManager().beginTransaction().setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out).replace(container, fragment, tag).commit();
You just need to have a TAG for each of your Fragment. Hope you will get the solution using this.
Related
I need to implement interestial ads when i move one tab to another. i use the below code to use that but interestial ad is not showing. How can i do that?
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.score,
R.drawable.fix,
R.drawable.tv
};
public static int int_items = 3 ;
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId(Ad_code.Interstitial2);
mInterstitialAd.loadAd(new AdRequest.Builder().addTestDevice("B167DCA4FD495BF41A2298FBC4894E56").build());
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
if(position == 1)
showInterstitial();
}
});
adapter.addFrag(new ScoreFrag(), "A");
adapter.addFrag(new FixtureFrag(), "B");
adapter.addFrag(new TVFrag2(), "C");
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) {
if(position == 0){
return new AFragment();
}
if(position == 1){
return new BFragment();
}
if(position == 2){
return new CFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "A";
case 1 :
return "B";
case 2 :
return "C";
}
return mFragmentTitleList.get(position);
}
}
final public void showInterstitial(){
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
if(mInterstitialAd.isLoaded()){
mInterstitialAd.show();
}
}
#Override
public void onAdClosed() {
}
});
}
Now i need to place interstitial ad when user go A to B fragment, B to C Fragment , C to B Fragment, B to A Fragment & C to A Fragment. This is just a test purpose so i need to place much ad here.
My AFragment Code
public FixtureFrag() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_one, container, false);
this.context = getActivity();
pbar = v.findViewById(R.id.progressBar1);
return v;
}
Where is the main issue? I am a beginner. So can anyone please give me the solution?
In your onPageSelected method remove if(position == 1)
public void onPageSelected(int position) {
//if(position == 1) ---> remove this
showInterstitial();
}
tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewpager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 6 || tab.getPosition() == 11 )
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
I have a problem in my Application, I load a fragment in my activity and in the fragment i used the ViewPager(for TabLayout) so i want to handle the BackPressed of ViewPager.
Because there is no OnKeyDown override method is available in fragment so i want the refrence of my Fragment ViewPager in my Parent Activty so i can handle this situation in onBackPressed() method Activity.
Activity Code :
fragment= new TabFragment();
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.containerView, fragment);
ft.commitAllowingStateLoss();
// ft.commit();
}
#Override
public void onBackPressed() {
if (isMainShown) {
// want the refrence of view pager so i can handle ViewPager on backPress
}
else {
//display tab fragment
}
//super.onBackPressed();
}
TabFragment :
public class TabFragment extends Fragment {
public TabFragment() {
// Required empty public constructor
}
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ; View x;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
x=inflater.inflate(R.layout.content_main_menu,null);
tabLayout=(TabLayout) x.findViewById(R.id.tabs);
viewPager =(ViewPager) x.findViewById(R.id.viewpager);
setupViewPager(viewPager);
//viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOffscreenPageLimit(1);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private void setupViewPager(ViewPager viewPager) {
MyAdapter adapter = new MyAdapter(getChildFragmentManager());
adapter.addFragment(new TabOne(), "TAb1");
adapter.addFragment(new TabTwo(), "Tab2");
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
final InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(x.getWindowToken(), 0);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private class MyAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
}
}......
add this code in your onBackPressed()
fragobjTab = (TabFragment) getSupportFragmentManager().findFragmentById(R.id.containerView);
try {
fragobjTab.onBackPressed();
}catch (Exception e){
e.printStackTrace();
}
And create a onBackPressed method in your tabFragment and setCurrentItem to the ViewPager:
public void onBackPressed()
{
// set page to your viewPager
// 0 is your first viewpager fragment
viewPager.setCurrentItem(0,true);
}
As per this accepted answer, I was able to get my tabLyout as below:
What do I need now, is to be able to change the buttons text based on the fragment position, for example if the position is zero, the Back should not appear, and if the position is the last, the Next should be replaced by Done
I have used the ViewPager.OnPageChangeListener but did not work for me, below is the full code:
public class Slider extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private Button leftBtn, rightBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_up);
leftBtn = (Button) findViewById(R.id.left_btn);
rightBtn= (Button) findViewById(R.id.right_btn);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
// This is not working, even the `Toast` not appearing
private ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(Slider.this, "Current position: "+position, Toast.LENGTH_SHORT).show();
if (position == 0) {
leftBtn.setText("");
}
if (position == 3) {
rightBtn.setText("DONE");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Tab1(),"");
adapter.addFrag(new Tab2(),"");
adapter.addFrag(new Tab3(),"");
adapter.addFrag(new Tab4(),"");
viewPager.setAdapter(adapter);
}
static 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);
}
}
public void next_fragment(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
}
public void previous_fragment(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
}
public void start_app(View view) {
startActivity(new Intent(Slider.this, TrustedNumber.class));
finish();
}
}
It's because you haven't added the listener to the viewpager
viewPager.addOnPageChangeListener(listener);
Hello I'm implementing a dynamic TabLayout using a single fragment, i have manage to create the tabs so far but there is a problem using a single fragment. When im changing the tabs the fragment view is not updating repeatedly, although im updating the data in the fragment's onCreateView method based on the tab selection. I have a recyclerview in the that fragment which should change according to the tab selection. SO can anyone help me with it or do anyone have a better way of approach?
TabView Activity
public class SubCategory extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
Activity a;
String url;
List<CategoryEncapsulation> categories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_category);
a=this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
categories=((MyshinzGlobal)getApplicationContext()).getCategoryList();
setupViewPager(viewPager);
((MyshinzGlobal)getApplicationContext()).setCategory_id(categories.get(0).getCategory_id());
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
try {
for (int i = 0; i < categories.size(); i++) {
try {
adapter.addFragment(new ListFragment(), categories.get(i).getCategory_name());
} catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
((MyshinzGlobal)getApplicationContext()).setCategory_id(categories.get(position).getCategory_id());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
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 int getItemPosition(Object object) {
return super.getItemPosition(object);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment class
public class ListFragment extends Fragment{
String category_id;
Activity a;
RecyclerView rv;
SubCategoryAdapter sca;
List<ParentListItem> parentListItems;
List<CategoryEncapsulation> categories = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.sub_category_fragment, container, false);
a=getActivity();
categories=((MyshinzGlobal)a.getApplicationContext()).getCategoryList();
category_id=((MyshinzGlobal)a.getApplicationContext()).getCategory_id();
parentListItems= new ArrayList<>();
Toast.makeText(getActivity(), String.valueOf(category_id), Toast.LENGTH_SHORT).show();
rv= (RecyclerView) view.findViewById(R.id.recycler_view);
for (int i=0; i<categories.size();i++){
if(categories.get(i).getCategory_id().equals(category_id)){
parentListItems=categories.get(i).getParentListItems();
}
}
sca=new SubCategoryAdapter(a,parentListItems);
rv.setAdapter(sca);
rv.setLayoutManager(new LinearLayoutManager(a));
//new GetAllSubCategoryTask(a,url,"1001").execute();
return view;
}
}
I have two solution for this.
1) make your view pager offset limit 0. Which default 1. If you are switching another fragment which not in offset, that fragment re-creating.
viewPager.setOffscreenPageLimit(0);
2) Tell your adapter, fragment has been changed. So your adapter will re-create its views again.
rv.notifyDataSetChanged();
I hope these will solve your problem.
First thing as you are using ViewPager, onCreateView() of Fragment will be called only when getItem() of FragmentPagerAdapter will be called.
If need to create a method in Fragment which will call RecyclerView.notifyDataSetChanged().
Check out updated code for both classes
TabView Activity
public class SubCategory extends AppCompatActivity {
//....
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
}
private void setupViewPager(ViewPager viewPager) {
//...
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
((MyshinzGlobal)getApplicationContext()).setCategory_id(categories.get(position).getCategory_id());
adapter.getItem(position).listUpdated();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<ListFragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public ListFragment getItem(int position) {
return mFragmentList.get(position);
}
//...
}
}
Fragment class
public class ListFragment extends Fragment {
//...
public void listUpdated() {
for (int i = 0; i < categories.size(); i++) {
if (categories.get(i).getCategory_id().equals(category_id)) {
parentListItems.clear();
parentListItems.addAll(categories.get(i).getParentListItems());
}
}
sca.notifyDataSetChanged();
}
}
I researched a lot and found no solution for my case.
This is my Activity:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//region FindViews
toolbar = (Toolbar) findViewById(R.id.toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (PagerSlidingTabStrip) findViewById(R.id.tabs);
//endregion
//region ViewPager
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupViewPager(viewPager);
viewPager.setOffscreenPageLimit(5);
// tabLayout.setupWithViewPager(viewPager);
tabLayout.setViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_red_primary));
break;
case 1:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_yellow_primary));
break;
case 2:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_green_primary));
break;
case 3:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_blue_primary));
break;
case 4:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_black_primary));
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
//endregion
extrasForFragment = new Bundle();
extrasForFragment.putInt("name", 3);
//region Get Extras from Intent
extras = getIntent().getExtras();
if (extras != null) {
userID = extras.getInt(StaticVariables.INTENT_USERID, -1);
Log.e("ISER", "dd " + userID);
OverViewFragment.newInstance().setArguments(extrasForFragment);
}
//endregion
setTitle("");
}
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);
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(OverViewFragment.newInstance(), getString(R.string.overview));
adapter.addFrag(new Fragment2(), getString(R.string.text));
adapter.addFrag(new Fragment3(), getString(R.string.text));
adapter.addFrag(new Fragment4(), getString(R.string.text));
adapter.addFrag(new Fragment5(), getString(R.string.text));
viewPager.setAdapter(adapter);
}
}
But it won't work.. THis is my fragment:
public class OverViewFragment extends Fragment {
public static OverViewFragment newInstance() {
return new OverViewFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Bundle b = getArguments();
if (b != null) {
Log.e("EXTRAS", "sind: " + b.toString() + " und: " + b.getInt("name", 0));
} else {
Log.e("FAIL", "...");
}
return inflater.inflate(R.layout.fragment_recyclerview, container, false);
}
}
But it didn't work. I tried this:
Send data from activity to fragment in android
and this:
Passing value between activity to fragment on android
But nothing want to work..
I hope for solutions. Thanks for any help!
The only place you call setArguments is at the line OverViewFragment.newInstance().setArguments(extrasForFragment); which is not used in your ViewPager. You want to set the arguments in your setupViewPager method, so like this:
Fragment overviewFrag = OverViewFragment.newInstance();
overviewFrag.setArguments(<args_bundle>);
adapter.addFrag(overviewFrag, getString(R.string.overview));