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

时间:2011-09-16 09:42:08

标签: android android-layout android-fragments

我有以下问题:

我有TabActivity在其中一个标签中显示FragmentActivity

FragmentActivity添加ListFragment时,点击ListFragment的项目时,会添加一个片段(也会添加到后台)并显示。

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

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

2 个答案:

答案 0 :(得分:20)

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

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.
    }
}

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

更新:已移除ViewGroupFrameLayout并使用LayoutInflater.from(),以及inflate()的第三个参数,而不是明确添加视图

答案 1 :(得分:0)

我相信如果您有适用于特定设备方向的布局,那么您只需要为它们提供相同名称,但将它们放在相应的资源目录中。 This link给出了一些解释。然后Android系统负责选择合适的资源,但如果需要,您可以自己处理。

相关问题