0

我希望我的应用程序在屏幕方向改变时重新建立蓝牙连接。我有一个保存 BT 串行服务数据等的 SavedState 对象,我可以使用 onRetainNonConfigurationInstance() 保存并使用 getLastNonConfigurationInstance() 恢复,但是当屏幕方向发生变化时,我的 TextView 字段不再更新。

我有两个用于布局的 xml 文件 - 一个在 layout-port 中,一个在 layout-land 文件夹中,分别用于重新格式化视图。两个 xml 文件中的 TextView ID 相同,只是它们的位置发生了变化。

如果我注释掉对覆盖的 onRetainNonConfigurationInstance() 的调用,TextViews 将再次可见,但我当然不能再自动重新连接到 BT 设备。

BT 服务在调用 onDestroy() 时停止,因此每次屏幕变化时必须重新建立。

覆盖对 onRestoreInstanceState() 和 onSaveInstanceState() 的调用似乎没有任何效果。

谁能指出我正确的方向?消失的视图是永久性的 - 即从一个方向更改并再次返回不会恢复 TextViews。

4

1 回答 1

0

When the device orientation changes, the views are taken off the screen (to be never shown again) and re-created. The same happens with the corresponding Activity. The now-invisible views and activity will be garbage-collected only when they are no longer referenced. The text in text views is preserved by the system, provided that the views have unique IDs. The fact that views are re-created means that you have to perform findViewById() again.

Now, from the MVC point of view, an Activity is a Controller. Your bluetooth connection definitely is a part of Model (it must survive orientation changes). So do not keep the bluetooth-related data in an Activity. You may use, say, a static variable, or a field in your Application subclass, or whatever else you find appropriate. As to the MVC View, it is what you specify via XML; in principle, you can define your custom classes like MyCustomButton, but usually you just reuse the existing stuff.

于 2013-10-25T05:53:28.203 回答