Viewpager Fragment 1 onCreateView is not always being called - java

When I swipe to or select Fragment1 (Fragment Numbers are 0-3) from its adjacent Fragments(0 , 2) in viewPager its onCreateView, or onCreate function is not being called.
But when I swipe back from Fragment3 or select Fragment1 when Fragment3 is active then both of these functions are being called. I am confused about why not from the adjacent Fragments its being called.
this is the code of Fragment who's onCreateView is not being called properly
`public class Fragment1 extends Fragment {
ShimmerFrameLayout shimmerFrameLayout ;
ConstraintLayout contentLayout;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getActivity(), "US News", Toast.LENGTH_SHORT).show();
Log.d("Called", "onCreate: ");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.us_news_fragment_layout , container , false);
shimmerFrameLayout = view.findViewById(R.id.usNewsShimmerLayoutId);
contentLayout = view.findViewById(R.id.usNewsLayoutId);
shimmerFrameLayout.startShimmerAnimation();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
shimmerFrameLayout.stopShimmerAnimation();
shimmerFrameLayout.setVisibility(View.GONE);
contentLayout.setVisibility(View.VISIBLE);
}
},3000);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("USNews", "onCreateView: ");
}
}`
This is the code in the main Activity for handling the events related to the viewpager
viewPager = findViewById(R.id.homeViewPagerId);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("US News"));
tabLayout.addTab(tabLayout.newTab().setText("Politics"));
tabLayout.addTab(tabLayout.newTab().setText("Live"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
viewPager.setCurrentItem(position);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
homePagerAdapter = new HomePagerAdapter(getSupportFragmentManager() , tabLayout.getTabCount());
viewPager.setAdapter(homePagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Toast.makeText(MainActivity.this, String.valueOf(tabLayout.getTabAt(position).getText()) + " is Active Now", Toast.LENGTH_SHORT).show();
homePagerAdapter.getItem(position);
}
#Override
public void onPageSelected(int position) {
homePagerAdapter.getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
homePagerAdapter.notifyDataSetChanged();
And this is the adapter of the ViewPager i am using
public class HomePagerAdapter extends FragmentStatePagerAdapter {
int NUM_OF_TABS;
private String[] tabTitles = new String[]{"Home", "US News", "Politics" , "Live"};
public HomePagerAdapter(#NonNull FragmentManager fm , int numberOfTabs) {
super(fm);
this.NUM_OF_TABS = numberOfTabs;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment0 homeFragment = new Fragment0 ();
return homeFragment;
case 1:
Fragment1 usNewsFragment = new Fragment1 ();
return usNewsFragment;
case 2:
Fragment2 politicsFragment = new Fragment2 ();
return politicsFragment;
case 3:
Fragment3 liveFragment = new Fragment3 ();
return liveFragment;
default:
return null;
}
}
#Override
public int getCount() {
return NUM_OF_TABS;
}
}
Please assist me about this. I'll be very thankful to you.
Thanks in advance

maybe this layout is already created and drawn? ViewPager have some handy option - keeps at least two additional Views/Fragments in memory for fast switching between pages. you can change this value to some higher only by calling setOffscreenPageLimit. by default its set to 1 - means that ViewPager keeps up to 3 Fragments - one to the left, one to the right and one currently visible on screen. with finger fling UI can just slide left/right page without drawing it from scratch (making almost always some small glitch/hang)
I bet you have two onCreate calls on start of your Activity - Fragment0s and Fragment1s. when you switch to Fragment1 you will see Fragment2 log, as ViewPager will prepare it for potential next swipe-left gesture. you can always use setOffscreenPageLimit(Integer.MAX_VALUE); for forcing all Fragments to be drawn at start and kept in memory (but only if these Fragments aren't to heavy, according to your tab names they might be...)
also homePagerAdapter.getItem(position); call in onPageSelected and onPageScrolled is unnecessary - it is creating new Frament and returning it, thats all, it isn't used. thats ViewPagers job to call this method (from attached adapter), take this Fragment and draw (on the screen or just render in memory for potential future use when user swipe left/right)

Related

Switching to a fragment from a fragment onClick()

I'm trying to create an application that has a similar framework to that of Snapchat, where I have three screens that can be swiped through. I have three screens (made with a fragment for each) and wish to slide to a screen on button press. Just to be clear, I have a table on one screen, from which a row is clickable and has a function that it calls onClick(). I wish to slide to the desired fragment using the mentioned function.
Fragment.Java:
public class ChatFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.chat_fragment_layout, container, false);
rootView.findViewById(R.id.row0).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
openfrag("1");
}
});
rootView.findViewById(R.id.row1).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
openfrag("2");
}
});
rootView.findViewById(R.id.row2).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
openfrag("3");
}
});
return rootView;
}
private void openfrag(String number){
}
I'm swiping through the fragments by using a PagerAdapter that extends FragmentPagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new MessageFragment();
case 1:
return new ChatFragment();
case 2:
return new CameraFragment();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
I have tried the replace method with fragmentmanager, but that is not what I want, I want it to act as if I swiped to that fragment.
Thanks for the help.
You can use simply this given code
String tag = "android:switcher:" + R.id.pager + ":" + 0;
AddStudentFragment f = (AddStudentFragment) getActivity().getSupportFragmentManager().findFragmentByTag(tag);
String tag1 = "android:switcher:" + R.id.pager + ":" + 1;
AssignSubjectFragment a = (AssignSubjectFragment) getActivity().getSupportFragmentManager().findFragmentByTag(tag1);
I managed to get it to work with a small addition to my MainActivity class outside the onCreate method. Whenever you need to switch to another fragment in your pager, simply call this function with the item index and true/false depending if you want it to smooth scroll or not.
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}

What is the correct way to call a method on ViewPager fragments when fragments become visible to user in android

I have a TabLayout that uses a ViewPager to show different fragments in tabs. I want to call a method (beginGettingData() to be precise) on the fragments when they become visible to user. There are two solutions that I used (and searched about for two days) and the result is I still get exceptions regarding fragment not being attached to the activity.
The first method I used is with fragment's setUserVisibleHint(true). I did something like this:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if (isVisibleToUser) {
if (shouldGetData) {
beginGettingData();
}
}
}
This approach gave me the activity not attached exception and it is true. since this method is being called before fragment's onCreateView method.
So I thought of a second approach and I used ViewPager's addOnPageChangeListener and called beginGettingData method in onPageSelected method of the listener like this:
#Override
public void onPageSelected(int position) {
TabFragment fragment = mAdapter.getItem(position);
fragment.beginGettingData();
}
This works for me if the activity is started from another activity in my application. For example if my MainActivity uses startActivity to start my TabLayout activity. But the problem occurs when the activity is restarted in anyway. For example when the user presses home button, not come back to the application for a long time (which makes android system to kill the activity), and then return to the activity by opening the application again. Or a more simple example would be when the screen rotates. In these scenarios, the onPageSelected method is called before onCreateView (unlike when the activity is tarted fresh) and then again I get the activity not attached exception.
I know I can check that if the fragment is added to the activity or not, but problem is that for the first time, there will be no data to show the user and thus it is not an option for me to use. I MUST call beginGettingData() somehow when the fragment is shown to the user.
So what do you suggest me to do?
ps: this is my complete code of the activity that hosts the TabLayout and ViewPager
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_files);
mViewPagerOnChangePagelistener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (!mDataList.get(position)) {
getSupportFragmentManager().executePendingTransactions();
TabFragment fragment = mAdapter.getItem(position);
fragment.beginGettingData();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
mViewPager = (ViewPager) findViewById(R.id.files_list_view_pager);
setupViewpager(mViewPager);
mViewPager.setOffscreenPageLimit(1);
mTabLayout = (TabLayout) findViewById(R.id.files_list_tabs);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(mViewPagerOnChangePagelistener);
mViewPager.post(new Runnable() {
#Override
public void run() {
mViewPagerOnChangePagelistener.onPageSelected(mViewPager.getCurrentItem());
}
});
}
private void setupViewpager(ViewPager viewPager) {
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
MediaFragment videoMediaFragment = new MediaFragment();
MediaFragment pictureMediaFragment = new MediaFragment();
Bundle videoMediaBundle = new Bundle();
Bundle pictureMediaBundle = new Bundle();
videoMediaBundle.putInt("media_type", MediaHelper.MEIDA_TYPE_VIDEO);
pictureMediaBundle.putInt("media_type", MediaHelper.MEDIA_TYPE_PHOTO);
videoMediaFragment.setArguments(videoMediaBundle);
pictureMediaFragment.setArguments(pictureMediaBundle);
mAdapter.addFragment(videoMediaFragment, "video");
mAdapter.addFragment(pictureMediaFragment, "picture");
viewPager.setAdapter(mAdapter);
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<TabFragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public TabFragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(TabFragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible) {
if(getActivity() != null){
if (shouldGetData) {
beginGettingData();
}
}
}
}
Try this ...

My fragmentClass get wrong page from ViewPager in medod onContextItemSelected

First. Sorry for my English.
I have Activity class with ViewPager as a field and a Fragment class. My activity is a host for a fragment. In Fragment I want to call context menu registered for ImageView. For that, I override 2 methods: onCreateContextMenu and onContextItemSelected.
Problem is:
When onCreateContextMenu is called I get the correct page (that
on the screen now).
But when onContextItemSelected is called I get another page (this
depend on what parameter is set in
ViewPager.setOffscreenPageLimit(int)). For example, if it set 3, the returned page will be those, that on 3 positions to the left or to the right from current that on the screen.
How can I fix it?
Thank you.
Activity code
public class CrimePagerActivity extends FragmentActivity {
private ViewPager mViewPager;
private ArrayList<Crime> mCrimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewPager);
setContentView(mViewPager);
mCrimes = CrimeLab.get(this).getCrimes();
mViewPager.setOffscreenPageLimit(4);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mViewPager.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
FragmentManager fm = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
UUID crimeId = (UUID) getIntent().getSerializableExtra(CrimeFragment.EXTRA_CRIME_ID);
for (int i = 0; i< mCrimes.size(); i++){
if (mCrimes.get(i).getId().equals(crimeId)){
mViewPager.setCurrentItem(i);
break;
}
}
}
}
and fragment code
public class CrimeFragment extends Fragment {
.......
private ImageView mPhotoView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
........
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mPhotoView = (ImageView) v.findViewById(R.id.crime_imageView);
registerForContextMenu(mPhotoView);
return v;
}
.........
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Log.i(TAG, mCrime.getTitle());
switch (v.getId()) {
case R.id.crime_imageView:
if (mCrime.getPhoto() != null)
getActivity().getMenuInflater().inflate(R.menu.crime_photo_context, menu);
break;
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.i(TAG, mCrime.getTitle());
switch (item.getItemId()) {
case R.id.menu_item_delete_photo:
getActivity().deleteFile(mCrime.getPhoto().getFilename());
PictureUtils.cleanImageView(mPhotoView);
mCrime.setPhoto(null);
return true;
}
return super.onContextItemSelected(item);
}
}
ViewPager.setOffscreenPageLimit(int);
This will prepare the pages at both sides to the left and right (neighbours).
By default it is 1.
So, in your case to get the current fragment created by the viewPager.
You can store the fragments when created in an SparseArray by overriding the instantiateItem() and destroyItem() callback of viewPager with position.
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getFragment(int position) {
return registeredFragments.get(position);
}
And where you want to get the current fragment, get it by using the getFragment() method by passing the position.

pass data to another fragment by swipe view with tab android studio,not button

Is it possible to pass a data from fragment to fragment by swipe?
There are many articles teaching us how to pass the data from fragment to fragment, but most of the article or questions had implemented OnClickListener in their first fragment, which used to pass value to another fragment.
But my case is pass the data from two fragments without any button click and finally save them in different tables by clicking button in the last fragment. What can I do to achieve this??
The flow is Information >> WorkForce >>WorkDetailsTable and save them to different table by one button click.
I have tried to work it out but I get NULL value in SQLite. I think I have miss out a lot but have no idea. PLEASE help me...I've been stuck at here for more than two days...Thanks
Tab.java
public class Tab extends ActionBarActivity implements ActionBar.TabListener {
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
public static String name = null;
public static String subContractors = null;
// will be used for data communication
public static Force force_bean;;
public static Info info_bean;
public static Force getForce(){
return force_bean;
}
public static void setForce(Force force){
force_bean=force;
}
public static Info getInfo(){
return info_bean;
}
public static void setInfo(Info info){
info_bean=info;
}
final Activity mActivity = (Activity) this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
info_bean = new Info();
force_bean = new Force();
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = ((AppCompatActivity) mActivity).getSupportActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
actionBar = ((AppCompatActivity) mActivity).getSupportActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Add New Tabs
actionBar.addTab(actionBar.newTab().setText("Information").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Work Force").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Work Details").setTabListener(this));
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return Information.newInstance("name");
case 1:
return WorkForce.newInstance("SubCon");
case 2:
return WorkDetailsTable.newInstance();
}
return null ;
}
#Override
public int getCount() {
return 3; //No of Tabs you can give your number of tabs
}
Informmation.java
public class Information extends Fragment implements View.OnClickListener {
private Spinner spinner, spinner2, spinner3;
private static String a;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View info = inflater.inflate(R.layout.information, container, false);
dialog = new DateDialog();
spinner = (Spinner)info.findViewById(R.id.spinner);
addItemsOnSpinner();
a= spinner.getSelectedItem().toString();
return info;
}
public static Information newInstance(String a)
{
Information fragment=new Information();
Bundle bundle=new Bundle();
bundle.putString("a",a);
fragment.setArguments(bundle);
return fragment;
}
public void addItemsOnSpinner() {
List<String> list = new ArrayList<String>();
list.add("1 ");
list.add("2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
WorkForce.java
public class WorkForce extends Fragment {
private static EditText txt1;
private static String subCon;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View work = inflater.inflate(R.layout.workforce, container, false);
txt1 = (EditText) work.findViewById(R.id.editText);
subCon = txt1.getText().toString();
return work;
}
public static WorkForce newInstance(String subCon) {
WorkForce f = new WorkForce();
Bundle bundle = new Bundle();
bundle.putString("subCon", subCon);
f.setArguments(bundle);
return f;
}
}
WorkDetails.java
private com.example.project.project.API.InfoAPI ts;
private com.example.project.project.API.WorkDetailsAPI WD;
private com.example.project.project.API.WorkForceAPI WF;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View workDetails = inflater.inflate(R.layout.tableworkdetails, container, false);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
spinnerTra = (Spinner) workDetails.findViewById(R.id.spinner6);
addItemsOnSpinner();
Button btn1 = (Button)workDetails.findViewById(R.id.button2);
WD = new com.example.project.project.API.WorkDetailsAPI(getActivity());
ts = new com.example.project.project.API.InfoAPI(getActivity());
WF = new com.example.project.project.API.WorkForceAPI(getActivity());
a1 = spinnerTra.getSelectedItem().toString();
Bundle bundle = new Bundle();
final String name = bundle.getString("a");
final String subContractors = bundle.getString("subCon");
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
add(name, subContractors);
}
});
return workDetails;
}
public void add(String name,String subContractors)
{
Toast.makeText(getActivity(),+name+subContractors, Toast.LENGTH_SHORT).show();
ts.insertTimeSheet(name);
WF.insertWorkForce(subContractors);
}
Note: My case is pass the data from two fragments without any button click and finally save them in different tables by clicking button in the last fragment.
If I understand your problem correctly, you are essentially implementing something a little bit like a "Wizard" where each step passes information to the next step as you swipe between the tabs or select them.
So in reality your problem is how to get the information out of a fragment when it is deselected and into a fragment when selected.
At the simplest level I would suggest your activity holds the "master" copy of all of the information and passes it into/takes it from each fragment in your tab pager adapter.
You would need some kind of "Domain" object to hold all the information you need to collect. Each tab would only update the bits of information it cares about..
public class WorkData {
string information;
string subCon;
... etc..
}
You add an instance of this to hold the master copy to your "tab" activity:
public class Tab extends ActionBarActivity implements ActionBar.TabListener {
...
WorkData workData = new WorkData();
...
I would then suggest a simple interface that each of your "tab" fragments implement; something like:
public interface DataUpdate {
void setData(WorkData data);
WorkData getData();
}
Each of your tab fragments would implement this interface, updating the WorkData as required..
public class WorkForce extends Fragment implements DataUpdate {
...
private WorkData workData; // this fragment's "copy" of the data
...
#Override
public WorkData getData() {
this.workData.subCon = this.subCon; // Assuming subcon has been updated.. else use txt1.getText();
return this.workData;
}
#Override
public void setData(WorkData workData) {
this.workData = workData;
// Update this page's views with the workData...
// This assumes the fragment has already been created and txt1 is set to a view
txt1.setText(workData.subCon);
this.subCon = workData.subCon; // Actually could just use subCon in workData, but be aware that workData actually points to the Activity's copy (kinda makes getdata redundant.. but I like symmetry and couldn't be bothered making lots of copies of the object).
}
Then you just need to add the code to pass the data backwards and forwards.. in your "Tab" activity which looks like...
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
int position = tab.getPosition();
DataUpdate dataUpdate = (DataUpdate) TabAdapter.getItem(position);
// Pass the master workdata to the selected fragment
dataUpdate.setData(this.workData);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
int position = tab.getPosition();
DataUpdate dataUpdate = (DataUpdate) TabAdapter.getItem(position);
// Update the master workdata from the unselected fragment
this.workData = dataUpdate.getData();
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
// This might be pointless, but we'll do it anyway..
int position = tab.getPosition();
DataUpdate dataUpdate = (DataUpdate) TabAdapter.getItem(position);
// Pass the master workdata to the selected fragment
dataUpdate.setData(this.workData);
}
An important thing to notice here is that your TabPagerAdapter will create a new fragment every time you call getItem().. that will mean that we will never get any updates because each time we try to get the fragment it returns a new, empty fragment. We need to change this so that the fragments are still created when first asked for, but only created once so that we don't keep throwing away our work.
public class TabPagerAdapter extends FragmentStatePagerAdapter {
private static final int NUMBER_OF_TABS = 3;
private Fragment[] tabList = new Fragment[NUMBER_OF_TABS];
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
if (tabList[i] != null) {
// Return a tab we created earlier..
return tabList[i];
} else {
switch (i) {
case 0:
tabList[0] = Information.newInstance("name");
return tabList[0];
case 1:
tabList[1] = WorkForce.newInstance("SubCon");
return tabList[1];
case 2:
tabList[2] = WorkDetailsTable.newInstance();
return tabList[2];
}
}
return null ;
}
#Override
public int getCount() {
return NUMBER_OF_TABS;
}
Hope this helps. Good luck :-)
Although C James provides good tips to solve your problems, I would like to introduce another way without using implementing of interfaces. Please check below link out. If you use an event bus library such a http://square.github.io/otto/, you can easily pass data you want to share among fragments and even activities. Additionally, you can reduce a lot of code line since it only requires Sender(PUBLISHING), Receiver(Subscriber) while implementation of interfaces requires additional lines of code.
Here is a tutorial of Otto libarary.
http://www.vogella.com/tutorials/JavaLibrary-EventBusOtto/article.html
Hope it helps :)
I would more go the Observer Pattern way.
Each Fragments changes an POJO with is rendered in your Fragments in some way. You simply have to Observe the pojo in your Fragments. Changing Fragments will notify interested observers without knowing them.
I believe that's a much cleaner way to implement this.
Fragment A -> PojoInstance.setXY("foo");
Fragment A -> informs the Observers which e.b Informs Fragment B:
Fragment B will see the change tru the Observer.
Because ViewPagers or other Components will cache Fragments thats a way to get information in already created Fragments, even when their are not seen.
You could also try to use an EventBus where you pass the POJO around.
To transfer data from one fragment to another fragment when swipe is performed ,firstly you should get the view of the each fragment.here is the sample code that can help you out a bit.
write this code in Activity:
mviewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
mviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
adapter = ((SOFragmentPagerAdapter) mviewpager.getAdapter());
//getting the view of fragments at positions
if(position==0)
{
View v = null;
Fragment1=(Fragment1)adapter.getFragment(position);
v=fragment1.getMyView();//this is how you get the view
ListView lv=(ListView)v.findViewById(R.id.lv_services);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(SOListItemSelectedActivity.this,android.R.layout.simple_list_item_1,soRequestFragment.al_list_of_services);
lv.setAdapter(arrayAdapter);
}
if(position==1)
{
}
}
#Override
public void onPageSelected(int position) {
if(position==0)
{
View v = null;
soRequestFragment=(SORequestFragment)adapter.getFragment(position);
v=soRequestFragment.getMyView();
}
if(position==1)
{
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mviewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
and create a FragmentPagerAdapter as:
public class SOFragmentPagerAdapter extends FragmentPagerAdapter {
HashMap<Integer,Fragment> mPageReferenceMap;
int mNumOfTabs;
public SOFragmentPagerAdapter(FragmentManager fm,int mNumOfTabs) {
super(fm);
this.mNumOfTabs=mNumOfTabs;
mPageReferenceMap=new HashMap<Integer,Fragment>();
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Fragment1 fragment1=new tFragment1();
mPageReferenceMap.put(position,fragment1);
return fragment1;
case 1:
Fragment2 fragment2=new Fragment2();
mPageReferenceMap.put(position,fragment2);
return fragment2;
default:
return null;
}
}
public Fragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
#Override
public int getCount() {
return 2;
}}
In Fragments add the getmyview() which will return the view of that fragment as:
public void getmyview()
{
return myview;//myview is fragment view which you will return in oncreateview method
}
Note: Viewpager execute onpagescroll first and get the position 0,1 and when you scroll ,views at position 1,2 will execute and page selected 0 will execute.
For tabselections: Tabunselected,Tabselected Tab reselected is the sequence of execution.
so write accordingly in the respective positions of fragments.
Hope this helps you.

How to implement listener interface in fragment?

I am trying to communicate between an activity and the fragment that sits on top of it, I want new data (image/text - retrieved from the db) to be passed into the frag every time an onclick occurs (onclick is in the activity). I made a simple interface to test (let me know if this is not suitable for images or if it is too slow or inefficient), and I am trying to have it included in my fragment so when an onclick occurs the fragment changes the image and the text.
Here is the simple interface code:
public interface FragmentCommunicator {
public void passDataToFragment(String someValue);
}
Here is the activity code:
public class RandomActivity extends FragmentActivity implements ActivityCommunicator {
//viewpager adapter
private PageAdapter mAdapter;
private ViewPager viewPager;
//interface through which communication is made to fragment
public FragmentCommunicator fragmentCommunicator;
//Buttons for yes, no, skip
Button btnYesRandom, btnNoRandom, btnSkipRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random);
//set buttons
btnYesRandom = (Button) findViewById(R.id.btnYesRandom);
// Initializing pager
viewPager = (ViewPager) findViewById(R.id.random_pager);
//calling bundle to attach data to fragment
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
RandomFragment randFrag = new RandomFragment();
randFrag.setArguments(bundle);
//Setting up fragment
FragmentManager fm = getFragmentManager();
mAdapter = new PageAdapter(getSupportFragmentManager(), new UserUpVotesFragment(), randFrag, new UserDownVotesFragment());
viewPager.setAdapter(mAdapter);
// Here you would declare which page to visit on creation
viewPager.setCurrentItem(1);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
if(position !=1) {
//swiping to the right
if(position == 0) {
Log.e("Swiping", "SWIPING TO THE Right BUT RESET ERR");
getIntent().removeExtra("edttext");
}
//swiping to the left
if(position == 2) {
Log.e("Swiping", "SWIPING TO THE left BUT RESET ERR");
}
// RandomFragment randomFrag = (RandomFragment) getFragmentManager().findFragmentById(R.id.fra);
viewPager.setCurrentItem(1);
}
}
});
btnYesRandom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(fragmentCommunicator != null)
fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
}
});
}
Code for Fragment:
public class RandomFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//call data from activity bundle
String strtext = getArguments().getString("edttext");
View rootView = inflater.inflate(R.layout.fragment_random, container, false);
RelativeLayout random_frag_layout = (RelativeLayout) rootView.findViewById(R.id.random_frag_layout);
activityButton = (ImageView) rootView.findViewById(R.id.imagehere);
//setRetainInstance(true);
texthere = (TextView) rootView.findViewById(R.id.texthere);
texthere.setText(strtext);
return rootView;
}
//FragmentCommunicator interface implementation
public void passDataToFragment(String someValue){
activityAssignedValue = someValue;
Log.e("ACTIVITY", activityAssignedValue);
}
}
If you have only one fragment, then you can access it directly and send any data just via method: make your fragment a field and call your passDataToFragment() on it from activity.
To access an activity from fragment, call ((RandomActivity)getActivity()).activityMethod()
What is ActivityCommunicator?
If you wish to go down this route have your RandomActivity class implement the FragmentCommunicator interface, which should either be declared as an inner-public interface in the RandomFragment class say, or publicly (or package local) in its own file.

Categories