Pass fragments between activities

2019-04-24 23:06发布

问题:

I want to make an application that can support portrait and landscape. The layout has two panes, on the left is the options and the right shows the result. When an option is selected the right pane shows it. But for portrait there is not enough room, so a separate activity is needed. Each option produces a different type of fragment, so I don't want to make an activity for each option when all that changes between activities is what fragment is being added there. I want to pass a fragment from the main activity to the new one, how would I do this?

回答1:

I want to pass a fragment from the main activity to the new one, how would I do this?

You wouldn't. At most, you would follow @Ribose's answer -- pass a flag into the activity via an extra to indicate what set of fragments to create.



回答2:

EDIT: Moved what asker actually wants to top.

If you want to pass data to an Activity when creating it, call a version of Intent.putExtra() on the intent that is used in startActivity(). You can then use getIntent().getStringExtra() to (for example) get a string extra in the activity.

Say you have a piece of string data in your first activity called myString.

Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(EXTRA_NAME_CONSTANT, myString);
startActivity(intent);

Now in your new activity in onCreate you would do:

String myString = this.getIntent()
        .getStringExtra(EXTRA_NAME_CONSTANT, "default return value here");

A few notes:

  • For that EXTRA_NAME_CONSTANT, I do mean to make a string constant of the form "your.package.name.SomeString" for example "com.example.MyString". Personally I'd even use a resource (accessed in the form getString(R.string.extra_my_string)) for the extra's name. They recommend you prefix it with your package name.
  • You can put and get many types of data from strings to arrays to even serializable data.

Instead of making a separete activity for different layout orientations consider using resource qualifiers to provide alternative layouts.

To summarize, make two layouts in a structure like so:

/res/layout/yourlayout.xml
/res/layout-land/yourlayout.xml

Where both XML files are named the same. Then make your default portrait layout in one and a landscape version in the other.

When you inflate the layout in onCreate (and when it does so automatically on a layout change during runtime) it will select the correct layout for you.