Android片段中方向更改时布局更改

And*_*SRS 5 android android-layout android-fragments

请提出解决方案.

当我旋转我的片段时,它应该切换到横向模式并显示另一个布局.但是屏幕不会旋转到横向.

我的代码打击:

 <activity
        android:name=".activites.MainActivity"
        android:launchMode="singleInstance"
        android:configChanges="keyboardHidden|screenLayout|screenSize|orientation"
        />
Run Code Online (Sandbox Code Playgroud)

这是称为仪表板的主要布局,现在它处于纵向模式:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     View  view=View.inflate(getContext(), R.frag_dashboard,null);
     changeview= (ShimmerTextView)view.findViewById(R.id.changeview); 
     return view;
}
Run Code Online (Sandbox Code Playgroud)

当我旋转屏幕时,这个片段变为横向模式并设置另一个布局,pray_times是新的布局.

   @Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(getContext(), "landscape", Toast.LENGTH_SHORT).show();
        view=View.inflate(getContext(), R.layout.prayer_times,null);

    }
}
Run Code Online (Sandbox Code Playgroud)

我为pray_times创建layout_land

Uda*_*mal 10

这是旧问题,但我想分享我的解决方案.

如果您的片段在方向更改时没有重新加载的问题,您可以简单地重新加载.

layoutlayout-land文件夹中添加两个具有相同名称的布局.这将在加载时显示正确的布局布局,在onConfigarationChanged方法中设备旋转时的更改布局.

@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE || newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        try {
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (Build.VERSION.SDK_INT >= 26) {
             ft.setReorderingAllowed(false);
            }
            ft.detach(this).attach(this).commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Nir*_*uan 0

您需要做的就是在文件夹layout-land中打开一个新文件夹,并将与片段布局同名的 xml 放在那里,框架会知道在方向更改时res查找该文件夹。.xml查看此处了解详细信息。