質問

As a beginner android developer I have faced with the problem concerning the fragments and activities handling when screen orientation is changed.

This is my situation: I have two fragments (F_A and F_B). F_A contains ListView (LV), and F_B contains combination of several Views: Description of LV (lets call it as Desc).

When app runs in portrait mode first activity shows LV and after clicking on an item the second activity runs. In this case when the orientation of the screen is changed from portrait to landscape mode I want to change the layout to show both fragments as it is done when the app initially runs in landscape mode.

I hope the provided pieces of codes will not confuse my description of the situation more :)

first activity main_activity.java file contains:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // there is two actitivy_main.xml files
    // one in layout/ directory and the other one in layout-land/ directory.
    ...
}
@Override
public void respond (int index) {
    // this method got the second fragment if it is visible and not null. 
    // otherwise starts new activity for only description fragment (F_B)
}

second activity (for portrait mode only) DescriptionActivity.java file contains:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // saving some stuff for further handling when orientation will changed from port to land.
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_description); // This layout contains only F_B fragment
... //here some initialization is done for the description.
}

Considering that during the screen rotation the Life Cycle guard methods such as onPause(), onStart() etc. are called I think that I have to check the orientation in that methods then destroy the second activity and run the first: main_activity which will itself check what layout should be shown (in this case the layout from layout-land/ directory, I am not sure weather this is a good idea, so I think to ask for help to developers with more experience.

Many thanks in advance,

Arsen

役に立ちましたか?

解決

The best way to achieve what you want is described in Fragments Android documentation, there you have an example with the full explanation.

But just as an advice, you don't have to use 2 diff activities nor check the orientation of the device, you just have to create an activity_main.xml for diff configurations in layout-port (portrait layout) and layout-land (landscape layout) you can learn how in here: Supporting Different Screens and Orientations. I know it's kind of hard at the beginning but working with fragments is one of the best practices for android. Read those tutorials and you'll be able to achieve your goal. Good luck :)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top