Fragments - Do you have to use an Activity Wrapper around a fragment which comprises the whole Activity?

前端 未结 3 389
时光说笑
时光说笑 2021-02-04 01:54

Consider the sample app from developers.android.com

This describes using Fragments like so:

  • On a Phone you can use Fragment 1 on Activity A and fragment 2
3条回答
  •  粉色の甜心
    2021-02-04 02:14

    More generically you could create a fragment container class:

    public class SingleFragmentActivity extends Activity {
    
        public static final String FRAGMENT_NAME = "fragmentName";
        public static final String FRAGMENT_ARGUMENTS = "fragmentArguments";
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            String fragmentName = getIntent().getStringExtra(FRAGMENT_NAME);
            Fragment fragment = Fragment.instantiate(this, fragmentName);
            Bundle fragmentArguments = getIntent().getBundleExtra(FRAGMENT_ARGUMENTS);
            fragment.setArguments(fragmentArguments);
            getSupportFragmentManager().beginTransaction().replace(android.R.id.content,fragment, "tag").commit();
        }
    }
    

    now you use this class to instantiate any fragment as a standalone activity:

    public void showFragmentAsActivity() {
        Intent intent = new Intent(this, SingleFragmentActivity.class);
        intent.putExtra(SingleFragmentActivity.FRAGMENT_NAME, MyFragment.class.getName());
        intent.putExtra(SingleFragmentActivity.FRAGMENT_ARGUMENTS,MyFragment.getArgumentsBundle("a string argument"));
        startActivity(intent);
    }
    

提交回复
热议问题