How to detect orientation change in layout in Android?

后端 未结 10 2177
挽巷
挽巷 2020-11-22 09:36

I just implemented a orientation change feature - e.g. when the layout changes from portrait to landscape (or vice versa). How can I detect when the orientation change event

10条回答
  •  无人及你
    2020-11-22 09:45

    Just wanted to show you a way to save all your Bundle after onConfigurationChanged:

    Create new Bundle just after your class:

    public class MainActivity extends Activity {
        Bundle newBundy = new Bundle();
    

    Next, after "protected void onCreate" add this:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                onSaveInstanceState(newBundy);
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                onSaveInstanceState(newBundy);
            }
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBundle("newBundy", newBundy);
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        savedInstanceState.getBundle("newBundy");
    }
    

    If you add this all your crated classes into MainActivity will be saved.

    But the best way is to add this in your AndroidManifest:

    
    

提交回复
热议问题