使用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 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) {
}
}
然后用这个基类
public class MainActivity extends BaseActivity {
...
@Override
public void onScreenOrientationChanged(int orientation) {
// Do something when screen orientation changed
}
}
完成延长活动!
你的意思是,如果它从风景切换到肖像或反之亦然? – Pengume
是不是这个线程相同? :http://stackoverflow.com/questions/4843809/how-do-i-detect-screen-rotation – Viren
在onConfigurationChanged方法中,您可以检测哪种类型的ConfigurationChanged发生,如屏幕旋转。 – mikepenz