方向改变 - 更新 UI
我在我的应用程序中使用加速度计的数据。如果设备的角度改变,屏幕方向也应该改变。 为了改变方向,我有两种布局,一种用于纵向,一种用于横向。
当方向改变时,调用一个函数来改变布局:
setContentView(R.layout.landscape);或 setContentView(R.layout.portrait);
这工作正常,但我对按钮或切换按钮等几个 UI 元素有问题。 我在 onCreate 方法中为它们初始化一个 onClickListener,每次方向更改时我都会初始化一个新的 onClickListener。
不幸的是,我无法再更改 ToggleButtons 的状态。
我该如何解决这个问题?
I use data of the accelerometer in my app. If the device´s angle is changed the screen orientation should change.
In order to change the orientation I have 2 layouts, one for portrait and one for landscape.
When the orientation changes a function is called that changes the layout with:
setContentView(R.layout.landscape); or setContentView(R.layout.portrait);
This works fine but I have a problem with several UI elements like buttons or ToggleButtons.
I initialize a onClickListener in the onCreate Method for them and each time the orienation gets changed I initialize a new onClickListener.
Unfortunately I can´t change the state of ToggleButtons anymore.
How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
/layout-land
和/layout-port
,手机会在方向改变时自动为您切换。请参阅http://developer.android.com/guide/practices/screens_support.html# DesigningResources
至于切换按钮,请参阅
onRetainNonConfigurationInstance()
http://developer.android.com/reference/android/app /Activity.html#onRetainNonConfigurationInstance%28%29
you can use
/layout-land
and/layout-port
and the phone will automatically switch them for you on orientation change. seehttp://developer.android.com/guide/practices/screens_support.html#DesigningResources
as for the toggle buttons, see
onRetainNonConfigurationInstance()
http://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance%28%29
正如 Bill Gary 上面所描述的,为什么不让系统为您处理方向变化呢?此外,当您执行此操作时,标准系统小部件应自动保留其状态。请参阅此处了解管理自定义状态的原因和方式(如果您需要。
As described by Bill Gary above, why not just let the system take care of orientation changes for you? Also the standard system widgets should automatically preserve their state when you do this. See here for why and how to manage custom state, if you need to.