화면 회전을 감지하기 위해 onConfigurationChanged 메소드를 사용하는 것은 좋지 않습니다. 사용자가 화면을 회전 할 때이 활동의 구성 변경이 올바르게 작동하지 않습니다.
그래서이 솔루션을 사용하여이 문제를 해결합니다.
public class SampleActivity extends AppCompatActivity {
public static final String KEY_LAST_ORIENTATION = "last_orientation";
private int lastOrientation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
if (savedInstanceState == null) {
lastOrientation = getResources().getConfiguration().orientation;
}
}
@Override
protected void onStart() {
super.onStart();
checkOrientationChanged();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
lastOrientation = savedInstanceState.getInt(KEY_LAST_ORIENTATION);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_LAST_ORIENTATION, lastOrientation);
}
private void checkOrientationChanged() {
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation != lastOrientation) {
onScreenOrientationChanged(currentOrientation);
lastOrientation = currentOrientation;
}
}
public void onScreenOrientationChanged(int currentOrientation) {
// Do something here when screen orientation changed
}
}
하지만 내 프로젝트에 사용할 수있을만큼 코드 여전히 좋지 않다, 그래서 난 내 자신의 라이브러리 (https://github.com/akexorcist/ScreenOrientationHelper)이 코드를 적용했다.
compile 'com.akexorcist:screenorientationhelper:<latest_version>'
그런 다음 완료를이 기본 클래스
public class MainActivity extends BaseActivity {
...
@Override
public void onScreenOrientationChanged(int orientation) {
// Do something when screen orientation changed
}
}
로 활동을 확장이
public class BaseActivity extends AppCompatActivity implements ScreenOrientationHelper.ScreenOrientationChangeListener {
private ScreenOrientationHelper helper = new ScreenOrientationHelper(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
helper.onCreate(savedInstanceState);
helper.setScreenOrientationChangeListener(this);
}
@Override
protected void onStart() {
super.onStart();
helper.onStart();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
helper.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
helper.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onScreenOrientationChanged(int orientation) {
}
}
같은 기본 활동 클래스를 만들 수 있습니다!
가로에서 세로로 또는 그 반대로 전환하는 경우를 의미합니까? – Pengume
이 스레드가 같지 않습니까? : http://stackoverflow.com/questions/4843809/how-do-i-detect-screen-rotation – Viren
onConfigurationChanged 메서드에서 화면 회전과 같이 발생한 ConfigurationChanged 유형을 감지 할 수 있습니다. – mikepenz