How to rotate views on orientation change without recreating layout?

前端 未结 2 1166
耶瑟儿~
耶瑟儿~ 2020-12-24 08:03

This question has been asked before here but its answer is incorrect. I would like to rotate some views on screen orientation change, but I want to keep the layout unchanged

2条回答
  •  梦毁少年i
    2020-12-24 08:54

    The basics are actually a lot easier. Have a look at Handling Runtime Changes.

    First things first, by setting

    android:configChanges="orientation|keyboardHidden|screenSize"
    

    in your Manifest on your activity tag you can handle the orientation change yourself. (orientation should be enough, but there are sometimes issues where the event does not fire with that alone.)

    You then skip onCreate and instead onConfigurationChanged gets called. Overwrite this method and apply your layout changes here. Whether you change your linearLayouts orientation here or have a custom view handling layout for different screens itself is up to you and depends on your implementation.

    Animating will be a bit trickier, if it is even possilbe. A quick search says it is not.


    Update for comment "I only want to rotate some views themselves rather than rotating the layout"

    In theory it is possible to create your own layout and handle the drawing of your child views. I just tried it but could not produce any results in an appropriate time, but what you would need to do:

    • keep your last measured values use tags on the view or similar approaches to keep the last measurements and layouts, so that after the orientation change you can diff
    • await orientation change: trigger rotated drawing - rotate the canvas, layout the views with the previous dimensions, and draw the child views where they would have been before, and
    • start an animation interpolate from the last to the new values, rotating the canvas from the last to the new layout

    This is how I would do it.

提交回复
热议问题