Change Fragment layout on orientation change
Posted dongweiq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Change Fragment layout on orientation change相关的知识,希望对你有一定的参考价值。
Warning: this may be a pre-Lollipop answer.
A 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的主要内容,如果未能解决你的问题,请参考以下文章
Android开发 报错: xxx does not have a NavController set on xxx
Fragment的R.layout.xxx:kotlin与java的比较
使用 ViewPager#setCurrentItem() 时出现“java.lang.IllegalStateException: Can't change tag of fragment”错误