首页 > 其他 > 详细

Change Fragment layout on orientation change

时间:2016-04-01 17:51:39      阅读:211      评论:0      收藏:0      [点我收藏+]

Warning: this may be a pre-Lollipop answer.

Fragment doesn‘t get re-inflated on configuration change, but you can achieve the effect as follows by creating it with a FrameLayout and (re)populating that manually:

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

I‘m not particularly happy with the getActivity() and related calls here, but I don‘t think there‘s another way to get hold of those things.

Change Fragment layout on orientation change

原文:http://www.cnblogs.com/dongweiq/p/5345551.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!