Kostya  Khuta
Kostya Khuta

Reputation: 683

layout-land files does not works

I've got the following problem. My program is a stopwatch. I have res/layout/main.xml and res/layout-land/main.xml But it works wrong. When I turn my phone, the program stops. I think it calls onCreate again. I added following line to the Manifest

android:configChanges="keyboardHidden|orientation"

but after this layout activity doesn't load.

I have tried next example, but it doesn't work

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  int ot = getResources().getConfiguration().orientation;
  switch (ot) {
    case Configuration.ORIENTATION_LANDSCAPE:
     setContentView(R.layout.main_land);
     break;
    case Configuration.ORIENTATION_PORTRAIT:
     setContentView(R.layout.main);
     break;
  }
 Toast.makeText(this, "Helloo", Toast.LENGTH_SHORT).show();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
  // TODO Auto-generated method stub
  super.onConfigurationChanged(newConfig);

  int ot = getResources().getConfiguration().orientation;
  switch (ot) {
    case Configuration.ORIENTATION_LANDSCAPE:
     setContentView(R.layout.main_land);
     break;
    case Configuration.ORIENTATION_PORTRAIT:
     setContentView(R.layout.main);
     break;
  }
}

@Override
public Object onRetainNonConfigurationInstance() {
 // TODO Auto-generated method stub
 return super.onRetainNonConfigurationInstance();
}

Upvotes: 1

Views: 573

Answers (1)

Hardik Vora
Hardik Vora

Reputation: 414

When you include the following command in AndroidManifest.xml i.e., android:configChanges="orientation", you're manually disabling the default layout-change behaviour, which is to re-start your activity in the new orientation.

The very useful thing to know is that you will need to manually change the layout used when you get CONFIGURATION_LANDSCAPE/CONFIGURATION_PORTRAIT in onConfigurationChanged.

Note that according to the documentation of the Activity from the Android Developers Website, onConfigurationChanged is a 'last resort' option - it's generally better to persist state and let the system re-launch your app.

The link for referring is as follows:-Link for handling Configuration.I hope this works for you.

Upvotes: 1

Related Questions