Dilemma: when to use Fragments vs Activities:

后端 未结 14 906
失恋的感觉
失恋的感觉 2020-11-22 11:58

I know that Activities are designed to represent a single screen of my application, while Fragments are designed to be reusable UI layouts with log

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 12:13

    I use Fragments for better user experience. For example if you have a Button and you want to run let's say a webservice when you click it, I attach a Fragment to the parent Activity.

    if (id == R.id.forecast) {
    
        ForecastFragment forecastFragment = new ForecastFragment();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.main_content, forecastFragment);
        ft.addToBackStack("backstack");
        forecastFragment.setArguments(b);
        ft.commit();
    }
    

    In that way the user won't have to move in another activity.

    And secondly I prefer Fragments because you can handle them easily during rotation.

提交回复
热议问题