处理片段内的方向

Handling orientation inside fragment

我有一个 activity,我在其中加载了一个 fragment。假设我在 fragment layout(section A and B) 中有两个部分,但是当我切换到横向时,我只需要显示部分 A 。我怎么知道片段内的方向变化。

您可以重写 onConfigurationChanged 以在方向更改时收到通知 在您的片段下方添加代码 class:

@Override public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if(newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
        //landscape
    }else{
        //portrait
    }
}

当屏幕的方向改变时,Fragment 将被销毁并重新创建,所以 onDestroy()onCreate() 被调用。在您的 onCreate()onCreateView()(或任何您需要的地方)中,您可以使用以下代码检查当前屏幕旋转:

int screenRotation = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
        if(screenRotation == Surface.ROTATION_90 || screenRotation == Surface.ROTATION_270) {
            //LANDSCAPE
        } else {
            //PORTRAIT
        }

为此功能android 提供滑动窗格布局SlidingPaneLayout

并观看此教程也是官方 google 开发人员教程 https://www.youtube.com/watch?v=Jl3-lzlzOJI&t=1007s