passing data from one fragment to another fragment without changing fragment - java

I have one activity HomeActivity and I have HomePageFragment which have some categories with icon and title of data, when I click on any category I'm sending the clicked item Title name with bundle and opening MultipleFragment and I'm getting clicked title name from the previous fragment, on this multiple fragments I have viewpager inside it..
1) PostFragment,
2) TextFragment
now here's my main question that I want to send clicked item title name to PostFragment and TextFragment,
HomeFragment
public void onItemClick(int position) {
MultiplePost multiplePost = new MultiplePost();
Bundle args = new Bundle();
Categories categoriesClicked = categoriesList.get(position);
args.putString(Title, categoriesClicked.getTitle());
args.putString(ImageUrl, categoriesClicked.getIcon());
multiplePost.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.main_frame,multiplePost)
.addToBackStack(null)
.commit();
}
MultiplePost
public class MultiplePost extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPageAdapter viewPageAdapter;
private View view;
private FragmentManager mFragmentManager;
public static String title ;
public MultiplePost() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_multiple_post, container, false);
title = getArguments().getString("title");
tabLayout = view.findViewById(R.id.tablayout_id);
viewPager = view.findViewById(R.id.viewPager_id);
viewPageAdapter = new ViewPageAdapter(getChildFragmentManager());
viewPageAdapter.AddFragment(new PostFragment(), "");
viewPageAdapter.AddFragment(new TextFragment(), "");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.photo);
tabLayout.getTabAt(1).setIcon(R.drawable.file);
PostFragment post = new PostFragment();
Bundle args = new Bundle();
args.putString("title", title);
post.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction();
.replace(R.id.main_frame, post)
.commit();// and this's changing whole fragment with PostFragment and
//so i can't see my viewpager on MultiplePost
return view;
}
}
ViewPagerAdapter
public class ViewPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> listFragment = new ArrayList<>();
private final List<String> listTitle = new ArrayList<>();
public ViewPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return listFragment.get(position);
}
#Override
public int getCount() {
return listTitle.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return listTitle.get(position);
}
public void AddFragment(Fragment fragment, String title){
listFragment.add(fragment);
listTitle.add(title);
}
}
How to send title onto PostFragment and TextFragment into viewpager

Related

How to handle recyclerview click event on fragment?

I, know this question is already asked on community but still I am not able to resolve my issue. That's why posting this again. How to pass data from recyclerview adapter to fragment. I have successfully pass data from adapter to the activity. But not able to get how to pass data from adapter to the fragment. I have two Parameters in my database (1) mSliderImage and (2) mTitle. The mSliderImage is shown on home fragment. but now I want when user click on particular image of slider a new fragment get opens and there mTitle will be shown. I successfully able to open new fragment on click of image-slider base on image position. But not getting how to pass mTitle in that fragment. Please someone help me the whole code because I have to submit this college level project by 17th of January. I am only posting the important code not my whole code. I just want coding solution of how to pass mSliderTitle from adapter to the fragment. when I click on some image of Image Slider.
Below is my code:
In Model I have passed 2 Getters ans Setters already mentioned above. (1) mSliderImage and (2) mTitle.
Slider Adapter:
public class SliderImageAdapter extends SliderViewAdapter<SliderImageAdapter.SliderAdapterVH>{
public List<Banner> bannerList;
public Context context;
private OnItemClicked onClick;
public interface OnItemClicked {
void onItemClick(int position);
}
public SliderImageAdapter(Context context, List<Banner> bannerList, OnItemClicked onClick) {
this.bannerList = bannerList;
this.context = context;
this.onClick = onClick;
}
#Override
public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_myshop, parent, false);
return new SliderAdapterVH(inflate);
}
#Override
public void onBindViewHolder(final SliderAdapterVH viewHolder, final int position) {
Glide.with(viewHolder.itemView)
.load(bannerList.get(position).getmSliderImage())
.into(viewHolder.imageViewBackground);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClick(position);
}
});
}
#Override
public int getCount() {
return bannerList.size();
}
public int getItemPosition (Object object) {
return POSITION_NONE;
}
public void setOnClick(OnItemClicked onClick) {
this.onClick = onClick;
}
class SliderAdapterVH extends SliderViewAdapter.ViewHolder {
View itemView;
ImageView imageViewBackground;
public SliderAdapterVH(View itemView) {
super(itemView);
imageViewBackground = itemView.findViewById(R.id.iv_auto_image_slider);
this.itemView = itemView;
}
}
Home Fragment: (Here Image Slider is Shown. and I want when user click a new fragment get open and show mTitle).
public class HomeFragment extends Fragment implements SliderImageAdapter.OnItemClicked {
private SliderImageAdapter sliderImageAdapter;
private List<Banner> bannerList;
bannerList = new ArrayList<>();
sliderImageAdapter = new SliderImageAdapter(getActivity(), bannerList, this);
#Override
public void onItemClick(int position) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container_dashboard, SliderClickFragment.newInstance());
ft.addToBackStack(null);
ft.commit();
}
Slider Click Fragment XML:
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/mSliderTitle"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Slider Click Fragment Java: (Here I want to show mTitle when user click on image)
public class SliderClickFragment extends Fragment {
public static SliderClickFragment newInstance() {
Bundle args = new Bundle();
SliderClickFragment fragment = new SliderClickFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.slider_click_listner,container,false);
return view;
}
}
Try this. I haven't tested but this flow should get what you are trying to achieve.
HomeFragment.java
public class HomeFragment extends Fragment implements SliderImageAdapter.OnItemClicked {
private SliderImageAdapter sliderImageAdapter;
private List<Banner> bannerList;
bannerList = new ArrayList<>();
sliderImageAdapter = new SliderImageAdapter(getActivity(), bannerList, this);
#Override
public void onItemClick(int position) {
//GET THE TITLE STRING HERE
String title = bannerList.get(position).getmSliderTitle();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//PASS THIS TITLE TO THE FRAGMENT INSTANCE LIKE THIS
ft.add(R.id.fragment_container_dashboard, SliderClickFragment.newInstance(title));
ft.addToBackStack(null);
ft.commit();
}
SliderClickFragment.java
public class SliderClickFragment extends Fragment {
//EDIT the newInstance Method definition to include title like this:
public static SliderClickFragment newInstance(String title) {
Bundle args = new Bundle();
//PASS THE STRING IN THE BUNDLE WHICH WILL THEN BE FETCHED IN ONCREATEVIEW LATER LIKE THIS
args.putString("title", title);
SliderClickFragment fragment = new SliderClickFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.slider_click_listner,container,false);
//GET THE STRING HERE AND THEN USE IT HOWEVER YOU LIKE
String title = getArguments().getString("title");
return view;
}
}

pass value from activity to fragment using bundle in tabbed activity

I am a java-illiterate, and still trying to develop a app for my personal use.
I have started with android-studio's "Tabbed-Activity", and mostly unaltered except a fragment and a bundle in MainActivity.
Here are my codes:
MainActivity
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//FloatingActionButton fab = findViewById(R.id.fab);
Bundle bundle = new Bundle();
bundle.putDouble("loclat", 25.4358);
bundle.putDouble("loclang",81.8463);
Fragment SunFragment = new SunFragment();
SunFragment.setArguments(bundle);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}
SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position) {
case 0:
return new SunFragment();
//return PlaceholderFragment.newInstance(pos + 5);
case 1:
return PlaceholderFragment.newInstance(1);
//return SecondFragment.newInstance();
//return PlaceholderFragment.newInstance(pos + 1);
default:
return PlaceholderFragment.newInstance(2);
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 2 total pages.
return 3;
}
}
And finally, The SunFragment, where I want my bundled data from MainActivity:
public class SunFragment extends Fragment {
List<SunSession> sunsList;
Typeface sunfont;
Double Dlat;
Double Dlang;
//to be called by the MainActivity
public SunFragment() {
// Required empty public constructor
}
private static final String KEY_LOCATION_NAME = "location_name";
public String TAG ="SunFragment";
public String location;//="No location name found";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
location = savedInstanceState.getCharSequence(KEY_LOCATION_NAME).toString();
System.out.println("OnCreate location "+location);
// Dlat = getArguments().getDouble("loclat");
//Dlang = getArguments().getDouble("loclang");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_sun, container, false);
//onSaveInstanceState(new Bundle());
if (getArguments() != null) {
Dlat = getArguments().getDouble("loclat");
Dlang = getArguments().getDouble("loclang");
} else {
Dlat=23.1;
Dlang=79.9864;
}
Log.e("Lat", Double.toString(Dlat));
I have followed this blog to make it, but no value is passed. Kindly help.
NB. This is a better described, and detailed question of my earlier question, which I understand, needs more code to be shown.
In your MainActivity, your sunFragment is unused. Remove this part:
/*Bundle bundle = new Bundle();
bundle.putDouble("loclat", 25.4358);
bundle.putDouble("loclang",81.8463);
Fragment SunFragment = new SunFragment();
SunFragment.setArguments(bundle);*/
You have to set bundle to fragment inside your SectionsPagerAdapter
case 0:
Bundle bundle = new Bundle();
bundle.putDouble("loclat", 25.4358);
bundle.putDouble("loclang",81.8463);
Fragment sunFragment = new SunFragment();
sunFragment.setArguments(bundle);
return sunFragment;
But if you need to set the bundle to fragment from MainActivity. Then use a callback in that purpose.
This way you can pass data from your mainActivity to fragment
MainActivity onCreate method
adapter = new Adapter(getChildFragmentManager());
SquadsTeamListFragment teamA =
SquadsTeamListFragment.newInstance(teamAData,teamBData
adapter.addFragment(teamA, teamAName);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
use this adapter in your main activity
static class Adapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
Adapter(FragmentManager manager) {
super(manager);
}
#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);
}
}
receive data to fragment (SquadsTeamListFragment .java)
public static SquadsTeamListFragment newInstance(String playerList, String
oppPlayerList) {
SquadsTeamListFragment fragment = new SquadsTeamListFragment();
Bundle args = new Bundle();
args.putString(ARG_TEAM_DATA, playerList);
args.putString(ARG_OPP_TEAM_DATA, oppPlayerList);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
playerList = getArguments().getString(ARG_TEAM_DATA);
oppPlayerList = getArguments().getString(ARG_OPP_TEAM_DATA);
}
}

It is possible to add/remove tabs in ViewPager at run time?

public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG, "onCreateView");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// setting up the view pager and tab layout
mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
mTabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
PageAdapter adapter = new PageAdapter(getFragmentManager());
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
return rootView;
}
My custom pager adapter looks like this:
public class PageAdapter extends FragmentStatePagerAdapter {
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new GroupTabFragment(position);
}
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "Game"; // this is from a template, i have to
break; // return title dynamically
case 1:
title = "Movie";
break;
}
return title;
}
#Override
public int getCount() {
return 2; // the tabs number is a subject of change
} // i don't know it from the begining
}
The problem i have is that i have to add or remove a tab when a button is clicked, or something like this.
Each tab will display a classic list of objects.
Thank you.
There are 2 ways doing this although ViewPager is not suitable for dynamic removing:
1) Pass ArrayList<Fragment> data as parameter to PageAdapter
Then Adapter will look like this:
public class PageAdapter extends FragmentStatePagerAdapter {
private ArrayList<Fragment> data;
public PageAdapter(FragmentManager fm, ArrayList<Fragment> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
return data.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "Game"; // this is from a template, i have to
break; // return title dynamically
case 1:
title = "Movie";
break;
}
return title;
}
#Override
public int getCount() {
return data.size(); // the tabs number is a subject of change
} // i don't know it from the begining
}
to remove item you do in Activity\Fragment:
data.remove(fragmentId);
adapter.notifyDataSetChanged();
2) Recreate adapter every time you want to delete item. So you basically create new adapter with new data.
data.remove(fragmentId);
PageAdapter adapter = new PageAdapter(getFragmentManager(), data);
mViewPager.setAdapter(adapter);
Instead of using mTabLayout.setupWithViewPager(mViewPager); you can setup your tabs manually:
mTabLayout.addTab(mTabLayout.newTab().setText("Movie"));
mTabLayout.addTab(mTabLayout.newTab().setText("Game"));
mTabLayout.addTab(mTabLayout.newTab().setText("Audio"));
mTabLayout.setOnTabSelectedListener(this);
Removing is also easy: removeTabAt(int position) or removeTab(Tab tab)
Here I have found some better solution to remove all the views / fragments from the current context.
Here I have used TabLayout and ViewPage within Fragment.
So we need to clear tabs from TabLayout, views from ViewPage and fragments from FragmentManager.
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
FragmentManager fragmentManager = null;
public TabLayout tabLayout;
public ViewPager viewPager;
public ViewPagerAdapter(FragmentManager manager, TabLayout tabLayout, ViewPager pager) {
super(manager);
this.fragmentManager= manager;
this.tabLayout = tabLayout;
this.viewPager= pager;
}
public void removeAll() {
tabLayout.removeAllTabs();
viewPager.removeAllViewsInLayout();
viewPager.removeAllViews();
viewPager.setAdapter(null);
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
if (manager.getFragments() != null) {
manager.getFragments().clear();
}
viewPager.setAdapter(adapterPage);
viewPager.invalidate();
viewPager.requestLayout();
mFragmentList.clear();
mFragmentTitleList.clear();
}

How to change views in ViewPager Fragment

I have a ViewPager with fragments in my activity, each page has a textview, I want to change the text of the textview from the onCreate method in the activity that contains the viewpager. How should I go about doing that?
below is the code that would return a null object exception:
Fragment:
public class MyFragment extends Fragment {
private TextView textView;
public static MyFragment getInstance(){
return new MyFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
textView = (TextView) rootView.findViewById(R.id.textView);
return rootView;
}
public void setText(String text){
textView.setText(text);
}
}
Adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return MyFragment.getInstance();
}
#Override
public int getCount() {
return 3;
}
}
Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
MyFragment fragment = (MyFragment) adapter.getItem(0);
fragment.setText("Altered"); // and this returns null pointer exception
}
Thank you!
Most FragmentPagerAdapters will have an addFragment method and will keep track various fragments that are added to it via an internal object:
public class MyPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
As it stands, your implementation of getItem returns a new instance of MyFragment every time it is called. As such, MyFragment fragment = (MyFragment) adapter.getItem(0); is a new instance that will never be loaded into the ViewPager, will never be inflated, and hence has a null textView reference.
The other issue is that within the onCreate of your activity, the fragments have not yet been inflated, so the textView will be null unless you delay the call:
final MyFragment fragment = (MyFragment) mPagerAdapter.getItem(0);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
fragment.setText("Altered");
}
}, 100);
But really, why not just set it to the correct value when it is initialized?
Try This
Fragment:
public class MyFragment extends Fragment {
private TextView textView;
private String Text;
public MyFragment (String Text){
this.Text=Text;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
textView = (TextView) rootView.findViewById(R.id.textView);
textView.setText(Text);
return rootView;
}
}
Adapter :
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new MyFragment("Altered");
}
#Override
public int getCount() {
return 3;
}
}
Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}

How to get the position of the fragment in an Activity?

I am new to android. I have a sliding tab layout and a viewpager with a fragment. I have setup a basic link between these to switch tabs for a count of 5(i.e 5 tabs) The problem is that, in each of these tabs, I want to populate a listview using simplecursoradapter, for which I need the position of each fragment so that I could populate it accordingly. I have got the position in the fragment adapter class, but I am unable to pass it to the main activity. Also, How can I access DBadapter inside my fragment class to populate listview from the database? or is there some other way to do this? Below is my code. Any help is greatly appreciated. Thanks in advance.
public class myFragment extends Fragment{
private ListView mainList;
public static myFragment getInstance(int position){
myFragment MyFragment = new myFragment();
Bundle args = new Bundle();
args.putInt("position", position);
MyFragment.setArguments(args);
return MyFragment;
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_main_list,container, false);
mainList = (ListView)layout.findViewById(R.id.mainListView);
Bundle bundle = getArguments();
if(bundle!=null){
if(bundle.getInt("position")==0){
mainList.setBackgroundColor(getResources().getColor(R.color.primary500));
}
else if(bundle.getInt("position")==1){
mainList.setBackgroundColor(getResources().getColor(R.color.primary100));
}
else if(bundle.getInt("position")==2){
mainList.setBackgroundColor(getResources().getColor(R.color.primary700));
}
else if(bundle.getInt("position")==3){
mainList.setBackgroundColor(getResources().getColor(R.color.accent));
}
else if(bundle.getInt("position")==4){
mainList.setBackgroundColor(getResources().getColor(R.color.black));
}
}
return layout;
}
}
The Main Activity is as follows:
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
private ViewPager mPage;
private SlidingTabLayout mTabs;
DBadapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openDB();
toolbar = (Toolbar)findViewById(R.id.app_bar);
mPage = (ViewPager)findViewById(R.id.pager);
mTabs = (SlidingTabLayout)findViewById(R.id.tabs);
mFab = (FloatingActionButton)findViewById(R.id.fab);
setSupportActionBar(toolbar);
mPage.setAdapter(new myPagerAdapter(getSupportFragmentManager()));
mTabs.setViewPager(mPage);
}
public class myPagerAdapter extends FragmentPagerAdapter{
String[] tabs;
public myPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
myFragment MyFragment = myFragment.getInstance(position);
return MyFragment;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 5;
}
}
Use this method :
mPage.setOnPageChangeListener(new SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
// pos is the position of fragment that app showing
});
UPDATE
in your view pager adapter :
public Fragment getItem(int position) {
return new myFragment(position);
}
And in your fragment class :
public class myFragment extends Fragment{
private int pos
public void myFragment(int position){
this.pos = position;
}
// other code of your class

Categories

Resources