android - Pass data from Activity to Fragment in ViewPager

后端 未结 6 537
夕颜
夕颜 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: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.

提交回复
热议问题