Skip to content Skip to sidebar Skip to footer

How To To Send Data When Tab Is Selected Or Swipe?

I make a simple example of tab view using fragment and pager .I want to send to send data from one fragment to another fragment when user use tab button. I will give you more detai

Solution 1:

Here i am posting some code that might help, see the scenario is like this,

Your tabs are in your Activity so the click and swipe events would be handled there so declaring Interface will not help as you can not fire that Callback method in Tab swipe or click, so what you can do is create a method in FragmentOne which will return you ArrayList like below

publicArrayList<String> getData(){
   returnyourArrayList();
}

now in FragmentTwo create a method that will receive the ArrayList from FragmentOne like below

publicvoidsetData(ArrayList<String> yourArrayList){
  Toast.makeText(YourActivity.this,"ArrayList Size: "+yourArrayList.size(),Toast.LENGTH_SHORT).show();
}

Now about how to reference the Fragments in your Activity you can do something like this:

privatestatic String makeFragmentName(int viewPagerId, int index){
   return"android:switcher:" + viewPagerId + ":" + index;
}

Now in Tab Swipe or click call above method to Refer your fragments like below

ArrayList<String> yourArrayList = newArrayList<>();
FragmentOnefragmentOne= getSupportFragmentManger().findFragmentByTag(makeFragmentName(viewPagerId,0))
if(fragmentOne != null){
// get your arraylist using method of FragmentOne
    yourArrayList = fragmentOne.getData();
}
// refer your second fragment and set the above arraylist in thatFragmentTwofragmentTwo= getSupportFragmentManger().findFragmentByTag(makeFragmentName(viewPagerId,1))
if(fragmentTwo != null){
   fragmentTwo.setData(yourArrayList);
}

and you are done

see above 0 and 1 are index of fragments in adapter you will need to manage that let me know if you need further help

Solution 2:

In your first fragment named Fragmentone, do something like this:

if(callBack!=null){
     callBack.sendData(yourDataArrayList);
}

After doing this see what are you getting in log.

Post a Comment for "How To To Send Data When Tab Is Selected Or Swipe?"