Send Data from Activity to TabLayout fragments

前端 未结 1 1236
梦如初夏
梦如初夏 2021-01-26 03:18

I am designing a application in which i am facing problem,

I have a String date; in MainActivity.class and there are two fragments.

相关标签:
1条回答
  • 2021-01-26 03:31

    I got the answer of this question by searching over the internet. In this question i have to send string to MainActivity.java to fragments present on same Activity.

    Note : We have to create bundle object & have to send string(any dataType) by bundle.

    I have two fragments InBoundDate & OutBoundDate.

    In MainActivity.java in setupViewpager ()

     private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    
        //bundle
        bundle =new Bundle();
        bundle.putString("DATE","2017-10-19");
    
        InBoundDate frag_in = new InBoundDate();
        OutBoundDate frag_out = new OutBoundDate();
    
        frag_in.setArguments(bundle);
        frag_out.setArguments(bundle);
        adapter.addFrag(frag_in,"INBOUND");
        adapter.addFrag(frag_out,"OUTBOUND");
        viewPager.setAdapter(adapter);
    
    }
    

    ViewPager Adapter :

      //viewPager adapter ----- inbound & outbound
    public 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 android.support.v4.app.Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
    
        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    
        public void addFrag(android.support.v4.app.Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
    
        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
    

    In your Fragments get String by this way :

        String dateTxt;
        private Bundle bundle;
    
        //within OncreateView
         bundle = this.getArguments();
            dateTxt = bundle.getString("DATE");
            Log.e("DATE_FRAG_INBOUND",""+dateTxt);
    
    0 讨论(0)
提交回复
热议问题