我是否应该每次使用BottomNavigationView创建一个新的Fragment实例

时间:2019-01-02 18:13:04

标签: java android android-fragments bottomnavigationview

我正在尝试使用BottomNavigationView和Fragments创建一个Android应用程序。我的代码是:

public class MainActivity extends AppCompatActivity {

    //some code
    //some code
    //some code
    //some code

    private BottomNavigationView.OnNavigationItemSelectedListener
    mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    getFragmentManager().beginTransaction().replace(R.id.myframe, new myframeHome).commit();
                    return true;
                case R.id.navigation_dashboard:
                    getFragmentManager().beginTransaction().replace(R.id.myframe, new myframeDashboard).commit();
                    return true;
                case R.id.navigation_notifications:
                    getFragmentManager().beginTransaction().replace(R.id.myframe, new myframeNotifications).commit();
                    return true;
            }
            return false;
        }
    };
}

当用户在菜单上选择其他项目时,是否应该每次创建每个类的新对象?

像下面这样为每个类创建一个对象是一种好习惯吗?

public class MainActivity extends AppCompatActivity {

    //some code
    //some code
    //some code
    //some code

    private final Fragment home = new myframeHome();
    private final Fragment dashboard = new myframeDashboard();
    private final Fragment notifications = new myframeNotifications();

    private BottomNavigationView.OnNavigationItemSelectedListener
    mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    getFragmentManager().beginTransaction().replace(R.id.myframe, home).commit();
                    return true;
                case R.id.navigation_dashboard:
                    getFragmentManager().beginTransaction().replace(R.id.myframe, dashboard).commit();
                    return true;
                case R.id.navigation_notifications:
                    getFragmentManager().beginTransaction().replace(R.id.myframe, notifications).commit();
                    return true;
            }
            return false;
        }
    };
}

我应该使用哪种方法?

0 个答案:

没有答案