ooxio
ooxio

Reputation: 806

Android views and custom orientation change, what's the best way to handle?

I've an android app that has multiple views. I've disabled the automatic orientation switching by declaring android:configChanges="keyboardHidden|orientation|screenSize" for my activity.

Q1) How I should re-activate views in onConfigurationChanged()? It seems I need to reset the content view using setContentView method. Is there an alternative way to signal view that now you should inflate the landscape/portrait version of the layout? Some of my views contain quite complicated states/modeless dialogs etc that can appear any time so deleting the view object and re-instantiating it just doesn't sound right.

Q2) What's the best way in onConfigurationChanged() to know which view we should actually now activate i.e. what was focused when orientation change was initiated? I'm reluctant to rely on getCurrentFocus() as it can be null sometimes.

Upvotes: 1

Views: 4301

Answers (1)

curioustechizen
curioustechizen

Reputation: 10672

Q1) How I should re-activate views in onConfigurationChanged()?

As you mentioned, setContentView() is a good way to do this. Just remember to not always pass in a layout XML to this method. Instead, pre-inflate your layout into a View object and pass in that View object to setContentView. That way, you don't incur the cost of re-creating your view object on every orientation change.

The following is a sample code - may not work as-is; but meant to illustrate my point.

View mLandscapeView;
View myPortraitView

protected void onCreate(Bundle bundle){
    View myLandscapeView = getLayoutInflater().inflate(R.layout.my_landscape, null);
    View myPortraitView = getLayoutInflater().inflate(R.layout.my_portrait, null);
    //...
}

@Override
protected void onConfigurationChanged(Configuration config){
    if(config.orientation = Configuration.ORIENTATION_LANDSCAPE){
        //adjust mLandscapeView as needed
        setContentView(mLandscapeView);
    }

    // And so on ... 

}

Upvotes: 1

Related Questions