android--------Object-oriented universal interface that implements Activity and Fragment communication

foreword

When developing an app, Activity and Fragment are commonly used. Fragment is becoming more and more popular due to the convenience of operation, so the communication between Activity and Fragment, Fragment and Fragment cannot be avoided. We know that Fragment and Fragment cannot communicate directly, and It communicates through Activity. So how many communication methods do Activity and Fragment have, and what are their advantages and disadvantages?

A commonly used Activity and Fragment several communication methods

1 via Handle

Create an instance of the Handle mechanism in the Activity, and then pass the Handle instance through the constructor when creating the Fragment, so that the Fragment can transmit data to the Activity. But this has the following disadvantages:

(1) The coupling between Activity and Fragment is increased;

(2) The result of Activity processing cannot be fed back to Fragment in real time;

(3) The risk of memory leaks is increased;

2 Use static variables

The disadvantage is clearly increased memory consumption;

3 Use broadcast

Register broadcasts in Activity and Fragment respectively, so that communication can be achieved. Its disadvantages:

(1) Poor performance, with delay, the user experience will be poor;

(2) Standard broadcasting is generally used, with one sender and multiple receivers, overkill and poor performance;

(3) Code redundancy;

(4) The data disseminated is limited;

4 EventBus, rxBus (commonly known as universal oil)

Its use method refers to the official documentation. Its advantages are that it is simple and convenient to use, and its disadvantages are also obvious:

(1) EventBus and rxBus use the reflection mechanism internally, so their performance will be reduced;

(2) Code maintenance is difficult (newcomers who are unfamiliar with the project code have difficulty finding out how to call the implementation method);

(3) It is difficult to return data, they are one-way transfer;

5 Common interface

Write an interface in Fragment, let Activity implement this interface, and bind Activity and Fragment together through this interface, so that Activity and Fragment communicate in real time. In fact, Google recommends doing this, because each Fragment writes an interface. , it will cause code redundancy; if there are fewer Fragments, it is fine, if there are more, the Activity implements multiple interfaces, which makes the Activity head appear to be very large, and the naming of the interface is also a problem;

Two universal interface

If the code redundancy and interface naming can be solved on the basis of 5, we know that a function includes function name, function body, parameters, and return value, then we can achieve the above problems by building a simple framework.

 

Establish no (yes) parameters without (yes) four categories

 

 

After defining all the interface abstract classes, we are defining an interface management class to manage and call the corresponding function methods through the interface management class.

public class MainActivity extends AppCompatActivity{

    private ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
    private Fragment mCurrentFragment;
    private BottomNavigationBar mBottomNavigationBar;
    BadgeItem badgeItem;

    FragmentManager mFragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView(){
        mFragmentManager = getSupportFragmentManager();
        initFragemnt();
        showFragment(0);
        mBottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        mBottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        mBottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        mBottomNavigationBar.setBarBackgroundColor(android.R.color.white);
        badgeItem = new BadgeItem()
                .setBackgroundColor(Color.RED).setText("99")
                .setHideOnSelect(true); //设置被选中时隐藏角标
        mBottomNavigationBar
                .setActiveColor(R.color.colorAccent) //设置选中的颜色
                .setInActiveColor(R.color.colorPrimary);//未选中

        mBottomNavigationBar.addItem(new BottomNavigationItem(R.mipmap.ic_launcher, "首页"))
                .addItem(new BottomNavigationItem(R.mipmap.ic_launcher, "店铺"))
                .addItem(new BottomNavigationItem(R.mipmap.ic_launcher, "购物车"))
                .addItem(new BottomNavigationItem(R.mipmap.ic_launcher, "我的").setBadgeItem(badgeItem))
                .initialise();
        mBottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener(){

            @Override
            public void onTabSelected(int position) {
                showFragment(position);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });


    }

    private void showFragment(int page) {
        FragmentTransaction mFragmentTransaction = mFragmentManager
                .beginTransaction();
        if (mCurrentFragment != null) {
            mFragmentTransaction.hide(mCurrentFragment);
        }
        mCurrentFragment = fragmentArrayList.get(page);
        if (mCurrentFragment.isAdded())
        {
            mFragmentTransaction.show(mCurrentFragment);
        }else {
            mFragmentTransaction.add(R.id.fragmenta, mCurrentFragment,mCurrentFragment.getClass().getName());
        }
        mFragmentTransaction.commitAllowingStateLoss();
    }

    private void initFragemnt(){
        fragmentArrayList.add(new A());
        fragmentArrayList.add(new B());
        fragmentArrayList.add(new C());
        fragmentArrayList.add(new D());
    }

    public void setFunctionForFragment(final String tag){
        BaseFragment fragment=(BaseFragment)mFragmentManager.findFragmentByTag(tag);
        FunctionManager functionManager=FunctionManager.getInstance();
        fragment.setmFunctionManager(functionManager.addFunction(new FunctionNoParamNotResult(A.INTERFCE) {
            @Override
            public void function() {
                Toast.makeText(MainActivity.this,"无参无返回值"+tag,Toast.LENGTH_LONG).show();
            }
        }).addFunction(new FunctionNoParamWithResult<String>(B.INTERFCE) {
            @Override
            public String function() {
                Toast.makeText(MainActivity.this,"无参有返回值",Toast.LENGTH_LONG).show();
                return "张三";
            }
        }).addFunction(new FunctionWithParamNoResult<Integer>(C.INTERFCE) {
            @Override
            public void function(Integer o) {
                Toast.makeText(MainActivity.this,"有参无返回值"+o,Toast.LENGTH_LONG).show();
            }
        }).addFunction(new FunctionWithParamResultn<String>(D.INTERFCE) {
            @Override
            public String function(String o) {
                Toast.makeText(MainActivity.this,"有参有返回值"+o,Toast.LENGTH_LONG).show();
                return "zhangqie";
            }
        }));
    }

}

 

Finally, implement communication in Activity:

Effect picture:

 

       

 

 

Source code download Github: https://github.com/DickyQie/android-fragment-interface

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325002157&siteId=291194637