Activity restart on rotation Android

前端 未结 30 3929
花落未央
花落未央 2020-11-21 04:32

In my Android application, when I rotate the device (slide out the keyboard) then my Activity is restarted (onCreate is called). Now, this is proba

30条回答
  •  天涯浪人
    2020-11-21 04:54

    what I did...

    in the manifest, to the activity section, added:

    android:configChanges="keyboardHidden|orientation"
    

    in the code for the activity, implemented:

    //used in onCreate() and onConfigurationChanged() to set up the UI elements
    public void InitializeUI()
    {
        //get views from ID's
        this.textViewHeaderMainMessage = (TextView) this.findViewById(R.id.TextViewHeaderMainMessage);
    
        //etc... hook up click listeners, whatever you need from the Views
    }
    
    //Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        InitializeUI();
    }
    
    //this is called when the screen rotates.
    // (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.main);
    
        InitializeUI();
    }
    

提交回复
热议问题