更改方向更改时的片段布局

God*_*hen 4 android android-layout android-fragments

我有以下问题:

我有一个在其中一个标签TabActivity中显示的内容FragmentActivity.

FragmentActivity增加了一个ListFragment,当点击其中的项目时,ListFragment会添加一个片段(也会添加到后台)并显示.

现在我需要改变它的布局,Fragment以便在转向横向时更改.

但我完全无能为力地实施这一改变.我已经创建了在layout-land文件夹中更正布局.但设置它的正确点在哪里?

and*_*sel 20

警告:这可能是Lollipop之前的答案.

A Fragment不会在配置更改时重新膨胀,但您可以通过FrameLayout手动创建和(重新)填充来实现以下效果:

public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        FrameLayout frameLayout = new FrameLayout(getActivity());
        populateViewForOrientation(inflater, frameLayout);
        return frameLayout;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        populateViewForOrientation(inflater, (ViewGroup) getView());
    }

    private void populateViewForOrientation(LayoutInflater inflater, ViewGroup viewGroup) {
        viewGroup.removeAllViewsInLayout();
        View subview = inflater.inflate(R.layout.my_fragment, viewGroup);

        // Find your buttons in subview, set up onclicks, set up callbacks to your parent fragment or activity here.
    }
}
Run Code Online (Sandbox Code Playgroud)

我对getActivity()这里的相关电话并不是特别满意,但我认为没有其他办法来掌握这些事情.

更新:删除了ViewGroupto FrameLayout和used的强制转换LayoutInflater.from(),以及第三个参数,inflate()而不是显式添加视图.