how to to send data when tab is selected or swipe?

后端 未结 2 582
感情败类
感情败类 2020-12-22 06:36

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 mor

相关标签:
2条回答
  • 2020-12-22 07:12

    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.

    0 讨论(0)
  • 2020-12-22 07:14

    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

    public ArrayList<String> getData(){
       return yourArrayList();
    }
    

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

    public void setData(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:

    private static 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 = new ArrayList<>();
    FragmentOne fragmentOne = 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 that
    FragmentTwo fragmentTwo = 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

    0 讨论(0)
提交回复
热议问题