手动调用onCreateView片段

时间:2014-04-08 12:30:36

标签: android orientation fragment

在我的活动中,当方向发生变化时,我正在使用onConfigurationChanged:

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

     if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
     {
         Log.e(TAG,"onConfigurationChanged LANDSCAPE");
     }
     else
     {
         Log.e(TAG,"onConfigurationChanged PORTRAIT");
     }
 }

我想刷新我的片段视图,因此请让代码调用onCreateView。 有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:1)

解决方案是:

在我的抽象片段类中(从Fragment扩展)

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    final View view = getView();

    ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {


        @Override
        public void onGlobalLayout() {
            LayoutInflater inflater =  (LayoutInflater) ARApplication.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            populateViewForOrientation(inflater, (ViewGroup) getView());

            // Avoid infinite loop
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        }
    });
}

protected abstract void populateViewForOrientation(LayoutInflater inflater, ViewGroup view);

MyFragment的每个实例都必须实现populateViewForOrientation()方法:

protected void populateViewForOrientation(LayoutInflater inflater, ViewGroup viewGroup) {
    viewGroup.removeAllViewsInLayout();
    View subview = inflater.inflate(R.layout.welcome, viewGroup);
    // do all the stuff
}

答案 1 :(得分:0)

Fragment有自己的onConfigurationChanged回调,所以在Fragment中

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final ViewGroup root = (ViewGroup) inflater.inflate(R.layout.root_layout, null);
    initView(inflater, view);
    return view;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    final View view = getView();
    if (view != null) {
        initView(getActivity().getLayoutInflater(), (ViewGroup) view.findViewById(R.id.container));
    }
}

private void initView(final LayoutInflater inflater, final ViewGroup parent) {
    parent.removeAllViews();
    final View subRoot = inflater.inflate(R.layout.your_layout, null);
    parent.add(subRoot);
    //do all the stuff
}

root_layout是

的位置
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MergeRootFrame" />