android - Pass data from Activity to Fragment in ViewPager

后端 未结 6 538
夕颜
夕颜 2020-12-29 07:41

I have a simple Activity with TabLayout, ViewPager and 2 Fragments in it. Here\'s my Activity:

public class ManagementCompanyOverviewActivity extends BaseAct         


        
相关标签:
6条回答
  • 2020-12-29 08:07

    From Activity or ViewPager

    Bundle bundle = new Bundle();
    bundle.putParcelable(Keys.KEY_ITEM, cardResult);
    CardItemFragment cardItemFragment = new CardItemFragment();
    cardItemFragment.setArguments(bundle);
    

    From Fragment

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         getBundle();
    }
    
    
    private void getBundle() {
        bundle = getArguments();
        if (null != bundle) {
            if (bundle.containsKey(Keys.KEY_ITEM)) {
                cardResult = bundle.getParcelable(Keys.KEY_ITEM);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-29 08:08

    You can use newInstance method in your Fragment:

    public static MyFragment newInstance(String parameter) {
    
            Bundle args = new Bundle();
            args.putString("parameter", parameter);
            SfCategoryFragment fragment = new SfCategoryFragment();
            fragment.setArguments(args);
            return fragment;
        }
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if (getArguments() != null) {
                parameter = getArguments().getString("parameter");
            }
        }
    

    And in your Activity:

    instead of new MyFragment() use MyFragment.newInstance("yourParam");

    0 讨论(0)
  • 2020-12-29 08:10

    You could also in your adapter's constructor take in the data you want to display in the fragment and set the arguments before returning a new fragment

    public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private Weather weather;
    
    ViewPagerAdapter(FragmentManager fm, Weather weather) {
        super(fm);
        this.weather = weather;
    }
    
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                Bundle bundle = new Bundle();
                WeatherFragment weatherFragment = new WeatherFragment();
                bundle.putParcelable("weather", weather);
                weatherFragment.setArguments(bundle);
                return weatherFragment;
            case 1:
                return new PoemFragment();
            default:
                return new EmptyFragment();
        }
    }
    
    0 讨论(0)
  • 2020-12-29 08:13

    Fragment

    class SampleFragment : Fragment(), BaseFragmentInteraction {
        override fun updateFragmentData(data: String) {
            Toast.makeText(activity!!, data, Toast.LENGTH_SHORT).show()
        }
    }
    

    Interface

    interface BaseFragmentInteraction {
        fun updateFragmentData(data: String)
    }
    

    Activity:

    view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
    
            override fun onPageSelected(position: Int) {
                val fragmentItem = (view_pager.adapter as FragmentPagerAdapter).getItem(view_pager.currentItem)
                (fragmentItem as BaseFragmentInteraction).updateFragmentData("SomeData")
            }
    
            override fun onPageScrollStateChanged(state: Int) {}
    
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
        })
    

    The updateFragmetData method will be called in the current selected viewpager item fragment. You can also add a tag parameter to updateFragmetData so that you can be sure the right fragment instance is called. If required you can call isVisible in updateFragmetData implementation to make sure the fragment is visible.

    0 讨论(0)
  • 2020-12-29 08:16

    Okay, I did this.

    1 step: I created public interface in my Activity and setter for it:

    private OnAboutDataReceivedListener mAboutDataListener;
    
    public interface OnAboutDataReceivedListener {
            void onDataReceived(AboutCompanyViewModel model);
        }
    
    public void setAboutDataListener(OnAboutDataReceivedListener listener) {
        this.mAboutDataListener = listener;
    }
    

    2 step: I implemented this interface in my Fragment and set listener:

    public class AboutCompanyFragment extends BaseFragment implements ManagementCompanyOverviewActivity.OnAboutDataReceivedListener
    
        @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
    
                mActivity = (ManagementCompanyOverviewActivity) getActivity();
                mActivity.setAboutDataListener(this);
            }
    

    3 step: I overrided interface's method:

    @Override
        public void onDataReceived(AboutCompanyViewModel model) {
            mPBName.setVisibility(View.INVISIBLE);
            mPBDirector.setVisibility(View.INVISIBLE);
            mPBWebsite.setVisibility(View.INVISIBLE);
            mPBEmail.setVisibility(View.INVISIBLE);
            mPBPhone.setVisibility(View.INVISIBLE);
            mPBSchedule.setVisibility(View.INVISIBLE);
            mPBAddress.setVisibility(View.INVISIBLE);
    
            mTVName.setVisibility(View.VISIBLE);
            mTVDirector.setVisibility(View.VISIBLE);
            mTVWebsite.setVisibility(View.VISIBLE);
            mTVEmail.setVisibility(View.VISIBLE);
            mTVPhone.setVisibility(View.VISIBLE);
            mTVSchedule.setVisibility(View.VISIBLE);
            mTVAddress.setVisibility(View.VISIBLE);
    
            mTVName.setText(model.getCompanyName());
            mTVDirector.setText(model.getDirectorName());
            mTVWebsite.setText(model.getWebsite());
            mTVEmail.setText(model.getEmail());
            mTVPhone.setText(model.getPhone());
            mTVSchedule.setText(model.getWorkTime());
            mTVAddress.setText(model.getAddress());
        }
    

    That's it.

    0 讨论(0)
  • 2020-12-29 08:20

    Try this In activity

    public String sendData() {
            return YOUR_STRING;
        }
    

    In Fragment

    YOUR_ACTIVITY activity = (YOUR_ACTIVITY) getActivity();
    String getData = activity.SendData();
    
    0 讨论(0)
提交回复
热议问题