A Philosophy of Destruction

 

By default, when there is a change in the phone configuration that might affect resource selection, Android will destroy and re‑create any running or paused activities the next time they are to be viewed. While this could happen for a variety of different configuration changes (e.g., change of language selection), it will most likely trip you up mostly for rotations, since a change in orientation can cause you to load a different set of resources (e.g., layouts).

The key here is that this is the default behavior. It may even be the behavior that is best for one or more of your activities. You do have some control over the matter, though, and can tailor how your activities respond to orientation changes or similar configuration switches.

 

It’s All The Same, Just Different

 

Since, by default, Android destroys and re‑creates your activity on a rotation, you may only need to hook into the same that you would if your activity were destroyed for any other reason (e.g., low memory). Implement that method in your activity and fill in the supplied with enough information to get you back to your current state. Then, in (or , if you prefer), pick the data out of the and use it to bring your activity back to the way it was.

To demonstrate this, let’s take a look at the project. It, and the other sample projects used in this chapter, which are also found in the source code section of the Apress web site, use a pair of main.xml layouts, one in and one in for use in landscape mode. Here is the portrait layout:

 

while here is the similar landscape layout:

 

Basically, it is a pair of buttons, each taking up half the screen. In portrait mode, the buttons are stacked; in landscape mode, they are side‑by‑side.

If you were to simply create a project, put in those two layouts, and compile it, the application would appear to work just fine – a rotation (Ctrl‑F12 in the emulator) will cause the layout to change. And while buttons lack state, if you were using other widgets (e.g., ), you would even find that Android hangs onto some of the widget state for you (e.g., the text entered in the ).

What Android cannot automatically help you with is anything held outside the widgets.

This application is derived from the Pick demo used in Chapter 24. There, clicking one button would let you pick a contact, then view the contact. Here, we split those into separate buttons, with the “View” button only enabled when we actually have a contact.

Let’s see how we handle this, using :








Дата добавления: 2015-05-16; просмотров: 710;


Поиск по сайту:

При помощи поиска вы сможете найти нужную вам информацию.

Поделитесь с друзьями:

Если вам перенёс пользу информационный материал, или помог в учебе – поделитесь этим сайтом с друзьями и знакомыми.
helpiks.org - Хелпикс.Орг - 2014-2024 год. Материал сайта представляется для ознакомительного и учебного использования. | Поддержка
Генерация страницы за: 0.004 сек.