How to pass value from activity to fragment through view pager - android

I have an activity which uses view pager to switch between fragments. I have three fragments. While switching between these fragments i have to pass a string value to the fragment class to identify which fragment is selected.Because here I am using same fragment class for all the three fragments.
Here is my main activity.
public class mainActivity extends AppCompatActivity {
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
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) {
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 CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
here is my fragment class
public class RemainderFragment extends Fragment {
public RemainderEmailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}
I have tried intents and shared preferences to send data. but nothing worked. I have to get the String value in my fragment class. please help.

Please check the below code for sample required changes, I have modified your file and added some code to support your requirement.
Your Activity file
package com.adobe.reader.test;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.adobe.reader.R;
public class mainActivity extends AppCompatActivity
{
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
// Adding adapter
private ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// Let's say we need to call some method from fragment in the activity
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
remainderFragment.setString("Testing string");
}
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
}
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
remainderFragment.setString(value);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* This method will give you current fragment used in the viewpager.
* #return
*/
public Fragment getCurrentFragment()
{
Fragment fragment = null;
if (viewPager != null)
{
int currentFragmentIndex = viewPager.getCurrentItem();
if (adapter != null)
{
fragment = adapter.getItem(currentFragmentIndex);
}
}
return fragment;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
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) {
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 CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Your Fragment file
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.adobe.reader.R;
public class RemainderFragment extends Fragment
{
public String testingString;
public RemainderEmailFragment() {
// Required empty public constructor
}
// Sample method to be called from activity
public void setString(String testStr)
{
testingString = testStr;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}

Related

Content of ViewPager disapear after changing fragments

i'm back here with a new Question. So at the moment i created an app , that can switch from a fragment to another fragment when you click on a button. And inside those 2 fragments there is 2 viewPagers, whose create a custom number of buttons. But the problem is that when i switch from a fragment to the other one, and then i switch back , the content of the first one is no longer here. I tried a lot of things and nothing really help me. And i hope you can help me. Thanks in advance.
The Main Activity :
public class MainActivity extends AppCompatActivity {
String identifiant=null;
BottomBar bottombar;
ProgressBar progressBar;
ImageButton imageButton;
TextView nomson;
RelativeLayout aaaa;
FragmentWhizz fragmentWhizz;
FragmentPlaylist fragmentPlaylist;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autorisation();
fragmentWhizz = new FragmentWhizz();
fragmentPlaylist=new FragmentPlaylist();
Fragment fragment = new FragmentConnexion();
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();
bottombar = (BottomBar) findViewById(bottomBar);
aaaa = (RelativeLayout) findViewById(R.id.aaaa);
bottombar.setVisibility(View.INVISIBLE);
bottombar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if (tabId == R.id.tab_whiz) {
if(identifiant !=null){
changementFragment(fragmentWhizz);
}
}
if (tabId == R.id.tab_playlist) {
if(identifiant !=null){
changementFragment(fragmentPlaylist);
}
}
if (tabId == R.id.tab_reveil) {
if(identifiant !=null){
changementFragment(new FragmentReveil());
}
}
if (tabId == R.id.tab_param) {
if(identifiant !=null){
changementFragment(new FragmentParam());
}
}
}
});
}
public void changementFragment(final Fragment fragment){
runOnUiThread(new Runnable() {
public void run() {
fm = getFragmentManager();
FragmentTransaction ft =fm.beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
ft.replace(R.id.contentFragment, fragment).commit();
}
});
}
}
One of the 2 fragments that have the ViewPager:
public class FragmentPlaylist extends Fragment {
SlideToutesPlaylist fragmentAllPlaylist = new SlideToutesPlaylist();
SlideUserPlaylist fragmentUserPlaylist = new SlideUserPlaylist();
ViewPager mViewPager;
FloatingActionButton floatbutton;
private FragmentActivity myContext;
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.playlist, container, false);
DeplacerBoutton deplacer = new DeplacerBoutton(getActivity(),2);
floatbutton = (FloatingActionButton) myView.findViewById(R.id.floatingActionButton);
floatbutton.setOnTouchListener(deplacer);
mViewPager = (ViewPager) myView.findViewById(R.id.slide);
mViewPager.setAdapter(new SamplePagerAdapter(myContext.getSupportFragmentManager()));
Log.i("test","test");
return myView;
}
public class SamplePagerAdapter extends FragmentStatePagerAdapter {
SamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
/** Show a Fragment based on the position of the current screen */
if (position == 0) {
return fragmentAllPlaylist;
} else
return fragmentUserPlaylist;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
And finally one fragment displayed on the viewPager:
public class SlideToutesPlaylist extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.playlistall, container, false);
AffichePlaylist(myView);
return myView;
}
public void AffichePlaylist(View myView){
ExecHttpGetRequest requete = new ExecHttpGetRequest();
requete.execute("an IP");
LinearLayout aaa = (LinearLayout) myView.findViewById(R.id.aaa);
try {
if (requete.get() != null) {
JSONObject jsonObj = new JSONObject(requete.get());
JSONArray jSon = jsonObj.getJSONArray("valeurs");
for (int i = 0; i < jSon.length(); i++) {
JSONObject c = jSon.getJSONObject(i);
final String nom_playlist = c.getString("nom_playlist");
final String id_playlist = c.getString("id_playlist");
final String id_createur = c.getString("id_createur");
final String nb_vote = c.getString("nb_vote");
Button bouton = new Button(getContext());
bouton.setText(nom_playlist);
aaa.addView(bouton);
}
}
} catch (InterruptedException | ExecutionException | JSONException e) {
e.printStackTrace();
}
}
}
EDIT Ok finally i solved my problem with your solution but now i have this problem :
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:873)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:215)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1481)
at android.view.View.dispatchRestoreInstanceState(View.java:14762)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3123)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3129)
at android.view.View.restoreHierarchyState(View.java:14740)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:475)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1329)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
To inflate fragments inside another fragment you need tu use getChildFragmentManager() instead of
myContext.getSupportFragmentManager().
EDIT:
Use FragmentStatePagerAdapter as follows:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
//Check if the list is empty before return the size
#Override
public int getCount() {
return mFragmentList != null ? mFragmentList.size() : 0;
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
#Override
public CharSequence getPageTitle(int position) {
if (!mFragmentTitleList.isEmpty()) {
return mFragmentTitleList.get(position);
}
return "";
}
}
Then in your fragment just add the fragments you want to show in the viewPager:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
...
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);

Dynamic Tab containing List View Showing Adjacent Tab List

I'm having one parent Fragment whose class is Scrollbaltab which contains many dynamic child Fragment whose class is Fragment1 but when I'm scrolling tab "two" it shows tab "one" data and when scroll to tab "three" it shows tab "two" data please help me
//Dynamic Fragment
public class Fragment1 extends Fragment {
RecyclerViewAdapter recyclerViewAdapter;
HashMap<String, ArrayList<String>> item = new HashMap<String,ArrayList<String>>();
ArrayList onlineData1 = new ArrayList<>();
ArrayList onlineData2 = new ArrayList<>();
ArrayList onlineData3 = new ArrayList<>();
String titleName="";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflateView = inflater.inflate(R.layout.fragment_fragment1, null, false);
RecyclerView recyclerView = (RecyclerView) inflateView.findViewById(R.id.recyclerView);
recyclerView.removeAllViews();
recyclerViewAdapter = new RecyclerViewAdapter(this.getActivity() ,item.get(titleName));
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
//Layout manager for Recycler view
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity() ));
recyclerViewAdapter.notifyDataSetChanged();
return inflateView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int tab_position = Scrollbaltab.pos;
if(onlineData1.isEmpty())
{
onlineData1.clear();
}
if(onlineData2.isEmpty())
{
onlineData2.clear();
}
if(onlineData3.isEmpty())
{
onlineData3.clear();
}
item.clear();
onlineData1.add("one");
onlineData1.add("two");
onlineData1.add("three");
onlineData2.add("a");
onlineData2.add("b");
onlineData2.add("c");
onlineData3.add("x");
onlineData3.add("y");
onlineData3.add("z");
if(item.get("ONE")==null)
item.put("ONE",onlineData1);
if(item.get("TWO")==null)
item.put("TWO",onlineData2);
if(item.get("THREE")==null)
item.put("THREE",onlineData3);
String [] arr= new String[]{"ONE","TWO","THREE"};
if(tab_position>=0) {
titleName = arr[tab_position];
}
// set adpter
Log.d("values"+tab_position,item.get(titleName).toString());
}
}
//parent Fragment
public class Scrollbaltab extends AppCompatActivity {
Toolbar toolbar;
ViewPager viewPager;
TabLayout tabLayout;
ViewPagerAdapter adapter;
public static int pos=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollbaltab);
inlizeview();
}
private void inlizeview() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("scrolling tabbar");
setSupportActionBar(toolbar);
//both are use for set arrow back button in toolbar
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
// when click on arrow button of tootbar it finish the current activity
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
pos=position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(), "ONE");
adapter.addFragment(new Fragment1(), "TWO");
adapter.addFragment(new Fragment1(), "THREE");
viewPager.setAdapter(adapter);
}
}
//view pager adapter
public final List<Fragment> mFragmentList = new ArrayList<>();
public final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Log.e("DD","mFragmentList--"+mFragmentList.get(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 CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object){
return ViewPagerAdapter.POSITION_NONE;
}
}

How to switch between two fragments in android TabLayout?

how to switch between Fragment A and Fragment B in android TabLayout.
how to switch to next Fragment when Fargment Button Onclick is called.
Please help me
package com.digi.global.globalhub.fragment.offer;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.digi.global.globalhub.R;
import com.digi.global.globalhub.Utility.M;
import com.digi.global.globalhub.listener.FilterListener;
import com.digi.global.globalhub.listener.FragmentMove;
import com.digi.global.globalhub.listener.OfferFilter;
public class OfferFragmentActivity extends Fragment implements View.OnClickListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
PagerAdapter adapter;
ViewPager viewPager;
TabLayout tabLayout;
Context context;
Toolbar toolbar;
ImageView bizMenu;
PopupMenu popup;
public static OfferFragmentActivity mInstance = null;
public OfferFragmentActivity() {
// Required empty public constructor
}
public static OfferFragmentActivity newInstance(String param1, String param2) {
OfferFragmentActivity fragment = new OfferFragmentActivity();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
context = this.getContext();
mInstance = this;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view =inflater.inflate(R.layout.fragment_offer, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new PagerAdapter(getChildFragmentManager(), getContext());
tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
bizMenu = (ImageView) view.findViewById(R.id.bizMenu);
bizMenu.setVisibility(View.VISIBLE);
bizMenu.setOnClickListener(this);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.biz_ic, android.R.style.Theme_DeviceDefault));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.mipmap.ic_menu_white_36dp);
upArrow.setColorFilter(Color.parseColor("#B68426"), PorterDuff.Mode.SRC_ATOP);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(upArrow);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getString(R.string.Offers));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(final TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onClick(View v) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fragment = (Fragment) adapter.instantiateItem(viewPager, viewPager.getCurrentItem());
if(fragment instanceof OfferFilter){
switch (item.getItemId()) {
case R.id.bizTravel:
((OfferFilter) fragment).onFilterBizTravel("bizTravel");
return true;
case R.id.bizAssistance:
((OfferFilter) fragment).onFilterAssistance("bizAssistance");
return true;
case R.id.bizSolution:
((OfferFilter) fragment).onFilterSolution("bizSolution");
return true;
case R.id.partners:
((OfferFilter) fragment).onFilterPartner("partners");
return true;
case R.id.favoutites:
((OfferFilter) fragment).onFilterFavouritesBiz("favoutites");
return true;
}
return false;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentStatePagerAdapter {
String tabTitles[] = getResources().getStringArray(R.array.offerTab);
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
/* FragmentMove fragmentChanges = (FragmentMove) adapter.instantiateItem(viewPager, 2);
if(fragmentChanges instanceof FragmentMove) {
((FragmentMove) fragmentChanges).fragmentChanges();
}*/
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTWO();
case 2:
return new FragmentThree();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
/* public View getTabView(int position) {
View tab = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_layout, null);
TextView tv = (TextView) tab.findViewById(R.id.tabText);
tv.setText(tabTitles[position]);
return tab;
}*/
}
}
You can have a FragmentPagerAdapter to manager fragments and set this adapter into viewPager to slide fragments when you click on tabs or swipe to change tabs.
FragmentPagerAdapter:
public class TabLayoutViewPagerAdapter extends FragmentPagerAdapter {
private final int PAGE_COUNT = 3;
private final String[] mTabsTitle = {"Fragment A", "Fragment B, "Fragment C"};
private Context context;
private int[] mTabsIcons = {
R.drawable.a,
R.drawable.b,
R.drawable.c};
public TabLayoutViewPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
public View getTabView(int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(mTabsTitle[position]);
title.setSingleLine(true);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setImageResource(mTabsIcons[position]);
return view;
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
return new FragmentA();
case 1:
return new FragmentB();
case 2:
return new FragmentC();
}
return null;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return mTabsTitle[position];
}}
How you use it:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
TabLayoutViewPagerAdapter pagerAdapter = new TabLayoutViewPagerAdapter(getSupportFragmentManager(), this);
if (viewPager != null) {
viewPager.setAdapter(pagerAdapter);
}
You need a TabLayout:
mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
if (mTabLayout != null) {
mTabLayout.setupWithViewPager(viewPager);
//populate your tabs
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab != null)
tab.setCustomView(pagerAdapter.getTabView(i));
}
TabLayout.Tab tab = mTabLayout.getTabAt(0);
if (tab != null && tab.getCustomView() != null) {
tab.getCustomView().setSelected(true);
}
}
How to select a page:
private void selectPage(int pageIndex) {
mTabLayout.setScrollPosition(pageIndex, 0f, true);
viewPager.setCurrentItem(pageIndex);
}
Do not forget to create your customTab.xml.
Best regards.
In Fragment A's onClick() method, try this :
TabActivity tabs = (TabActivity) getParent();
tabs.getTabHost().setCurrentTab(2);

Pass data from one design tab to another tab

I am using material design tabs as follows :
Following is my MainActivity.class :
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("onPageSelected Called");
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
My ViewPagerAdapter is as follows :
public class ViewPagerAdapter extends FragmentPagerAdapter {
private static int count = 2;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
}
return null;
}
#Override
public int getCount() {
return count;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0 :
return "Tab One";
case 1 :
return "Tab Two";
}
return null;
}
}
and here are my Fragments :
This is my first fragment name is FragmentOne :
public class FragmentOne extends Fragment {
private EditText editText;
private Button btnSendData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT ONE");
View view = inflater.inflate(R.layout.fragment_one,container,false);
editText = (EditText) view.findViewById(R.id.et_name);
btnSendData = (Button) view.findViewById(R.id.btn_send);
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTwo fragment = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("username",editText.getText().toString());
fragment.setArguments(bundle);
getFragmentManager.beginTransaction.replace(R.id.frag_second,fragment).commit();
}
});
return view;
}
}
and here is another fragment with name FragmentTwo :
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT TWO");
View view = inflater.inflate(R.layout.fragment_two,container,false);
Bundle bundle = getArguments();
if(bundle!= null)
{
String value = getArguments().getString("username");
}
return view;
}
#Override
public void onResume() {
super.onResume();
System.out.println("onResume gets called");
}
}
In the second fragment i am getting data buts its adding another view with previous one.
see the image :
so I want to pass data from FragmentOne to FragmentTwo in two scenario :
1. I want to pass the data when i click on button and
2. When I swipe to FragmentTwo data should be passed
Also when I try to swipe to FragmentTwo nothing gets called in FragmentTwo ? why is it so ?
Also when I click to second tab nothing gets called .
Please help me how should i pass data to FragmentTwo on button click ?
following are layout files:
here is fragment_one
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:id="#+id/et_name"
android:hint="Username"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:padding="16dp"
android:text="Send Data"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:id="#+id/btn_send"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
and second fragment , fragment_second.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/second_frag"
android:gravity="center">
<TextView
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fragment Two"
android:id="#+id/textView2" />
Each fragment is associated with the parent activity. so you can't directly communicate from one fragment to another fragment. You will need to go through Parent Activity using interface.
Check this docs : https://developer.android.com/training/basics/fragments/communicating.html
On button click pass the value to methods in your custom interface and access those methods in second fragment.
when I try to swipe to FragmentTwo nothing gets called in FragmentTwo
For this you need to implement fragment life cycle - https://developer.android.com/reference/android/app/Fragment.html
UPDATE
Done with some modification in you code, just look at the foll. code -
Manifex.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity.java
package com.app.onkar.tabdemo;
import android.support.v4.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "ONE");
adapter.addFragment(new FragmentTwo(), "TWO");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("onPageSelected Called");
}
#Override
public void onPageScrollStateChanged(int state) {
}
public static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private static int count = 2;
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
}
return null;
}
#Override
public int getCount() {
return count;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab One";
case 1:
return "Tab Two";
}
return null;
}
}
}
FragmentOne.java
package com.app.onkar.tabdemo;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentOne extends Fragment {
private EditText editText;
private Button btnSendData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT ONE");
View view = inflater.inflate(R.layout.fragment_one,container,false);
editText = (EditText) view.findViewById(R.id.et_name);
btnSendData = (Button) view.findViewById(R.id.btn_send);
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTwo fragment = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("username",editText.getText().toString());
fragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
}
});
return view;
}
}
FragmentTwo.java
package com.app.onkar.tabdemo;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("IN FRAGMENT TWO");
View view = inflater.inflate(R.layout.fragment_two,container,false);
TextView txt2 = (TextView) view.findViewById(R.id.textView2);
Bundle bundle = getArguments();
if(bundle!= null)
{
String value = getArguments().getString("username");
txt2.setText(value);
}
return view;
}
#Override
public void onResume() {
super.onResume();
System.out.println("onResume gets called");
}
}
No change in Layout files. Just try above code - it is working exactly as you want. Hope it will help!
SCREENS
ViewPagerAdapter class
public class ViewPagerAdapter extends FragmentPagerAdapter {
private static int count = 2;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment fragmentone = new FragmentOne();
Bundle args = new Bundle();
args.putInt("code", 1);
fragmentone.setArguments(args);
return fragmentone;
break;
case 1:
Fragment fragmenttwo = new FragmentTwo();
Bundle args = new Bundle();
args.putInt("code", 2);
fragmenttwo.setArguments(args);
return fragmenttwo ;
break;
}
return null;
}
#Override
public int getCount() {
return count;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0 :
return "Tab One";
case 1 :
return "Tab Two";
}
return null;
}
}
args is the bundle object, you can put String int and other values to use these values in fragment use below code in onCreateView method of Fragment.
int codeForthisFragment = getArguments().getInt("code");
for button click:
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment secondFragment = new FragmentTwo();
Bundle args = new Bundle();
args.putInt("code", 2);
secondFragment.setArguments(args);
ft.replace(R.id.content_frame, secondFragment);
ft.commit();
In the second fragment i am getting data buts its adding another view with previous one. see the image
With reference to the answer by #Roy Miller(https://stackoverflow.com/users/5255021/roy-miller),
you can solve it by doing the follwing changes:
In MainActivity.java ,replace the follwing switch:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
}
return null;
}
With:
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return mFragmentList.get(0);
case 1:
return mFragmentList.get(1);
case 2:
return mFragmentList.get(2);
default:
return null;
}
}
And then, in FragmentOne.java
Replace this:
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTwo fragment = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("username",editText.getText().toString());
fragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
}
});
With:
btnSendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*This one FragmentCollection is a Singleton class that contains list of fragments, set it during initialization itself(code is attached below this code)*/
FragmentCollection fragmentCollection=FragmentCollection.getInstance();
FragmentTwo fragment = (FragmentTwo) FragmentCollection.getmFragmentList().get(2); //getting the second fragment
fragment.setText(editText.getText().toString()); //add this method in fragment two
}
});
Now inside FragmentTwo.java
Add the method:
public void updateTextView(String data){
Log.d("TabTwo","Update Text view");
TextView txt = (TextView)view.findViewById(R.id.textView2);
txt.setText(data);
}
At last, the singleton class i mentioned above:
public class FragmentCollection {
static FragmentCollection fragmentCollection=new FragmentCollection();
private final List<Fragment> mFragmentList = new ArrayList<>();
private FragmentCollection(){}
public static FragmentCollection getInstance(){
if(fragmentCollection!=null) {
return fragmentCollection;
}else {
return new FragmentCollection();
}
}
public void setmFragmentList(List<Fragment> mFragmentList){
this.mFragmentList.addAll(mFragmentList);
}
public List<Fragment> getmFragmentList(){
return mFragmentList;
}
}
The issue of getting older views overlapping is because of initializing the fragment again and again
like new FragmentTwo(); in more than one place.
So here we put it in a list and access it so only a single fragment is altered.
I am not able to go to first fragment from Second fragment . I am using tab layout
This is my code
By clicking button from 2nd Fragment
Bundle bundle = new Bundle();
bundle.putString("uniqueList1", uniqueList.get(0));
bundle.putString("uniqueList2", uniqueList.get(1));
bundle.putString("kycUniquesNo", kycUniqueNum);
CustBasicFormFragement fragObj = new CustBasicFormFragement();
fragObj.setArguments(bundle);
In 1st Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
binding = DataBindingUtil.inflate(inflater, R.layout.cust_basic_form_fragment, container, false);
view = binding.getRoot();
if (getArguments() != null) {
string1 = getArguments().getString("uniqueList1");
string2 = getArguments().getString("uniqueList2");
kycUnique=getArguments().getString("kycUniquesNo");
System.out.print(string1);
System.out.print(string2);
System.out.print(kycUnique);
return view;
}

Passing data from Activity with ViewPager its to Fragments

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));

Categories

Resources