Communicating between a fragment and an activity - best practices

后端 未结 9 1318
予麋鹿
予麋鹿 2020-11-22 02:45

This question is mostly to solicit opinions on the best way to handle my app. I have three fragments being handled by one activity. Fragment A has one clickable element th

相关标签:
9条回答
  • 2020-11-22 03:39

    You can create declare a public interface with a function declaration in the fragment and implement the interface in the activity. Then you can call the function from the fragment.

    0 讨论(0)
  • 2020-11-22 03:40

    I made a annotation library that can do the cast for you. check this out. https://github.com/zeroarst/callbackfragment/

    @CallbackFragment
    public class MyFragment extends Fragment {
    
        @Callback
        interface FragmentCallback {
           void onClickButton(MyFragment fragment);
        }    
        private FragmentCallback mCallback;
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt1
                    mCallback.onClickButton(this);
                    break;
                case R.id.bt2
                    // Because we give mandatory = false so this might be null if not implemented by the host.
                    if (mCallbackNotForce != null)
                    mCallbackNotForce.onClickButton(this);
                    break;
            }
        }
    }
    

    It then generates a subclass of your fragment. And just add it to FragmentManager.

    public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            getSupportFragmentManager().beginTransaction()
                .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), "MY_FRAGM")
                .commit();
        }
    
        Toast mToast;
    
        @Override
        public void onClickButton(MyFragment fragment) {
            if (mToast != null)
                mToast.cancel();
            mToast = Toast.makeText(this, "Callback from " + fragment.getTag(), Toast.LENGTH_SHORT);
            mToast.show();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:40

    There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.

    My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.

    You can subscribe to events in your activity and then you can post that events in your fragments etc.

    Here on my blog post you can find more detail about this pattern and also an example project to show the usage.

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