Cambio de orientación de la pantalla de la tableta: no se ha encontrado ninguna vista para id para Fragment

He mirado las preguntas relacionadas con mi problema en SO pero no pude averiguar cuál es el problema. Tenga conmigo si esto es un repost.

Esto es lo que estoy buscando:

Modo de retrato del teléfono

Modo de paisaje del teléfono

Los cambios de diseño para el teléfono funcionan bien, ya que implica las mismas vistas dentro del fragmento. El problema es cuando intento conseguir la disposición abajo en tabletas.

Modo de retrato de la tableta

Modo de paisaje de la tableta

Mi Estructura de Diseño

Activity_main.xml en modo retrato:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <include android:id="@+id/toolbar" layout="@layout/toolbar_with_spinner" /> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout> </LinearLayout> <ListView android:id="@+id/listview_drawer" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="start" android:background="@color/white" android:choiceMode="singleChoice" android:divider="@null" android:dividerHeight="0dp" /> </android.support.v4.widget.DrawerLayout> 

Activity_main.xml en modo horizontal:

 <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <include android:id="@+id/toolbar" layout="@layout/toolbar_with_spinner" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" android:orientation="horizontal" > <FrameLayout android:id="@+id/fragment_container" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="0.40" /> <FrameLayout android:id="@+id/detail_fragment_container" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="0.60" /> </LinearLayout> </LinearLayout> <ListView android:id="@+id/listview_drawer" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="@color/white" android:choiceMode="singleChoice" android:divider="@null" android:dividerHeight="0dp" /> </android.support.v4.widget.DrawerLayout> 

Fragment_main.xml

 <?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipeRefreshLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:orientation="vertical" android:padding="4dp" > <GridView android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:horizontalSpacing="0dp" android:numColumns="3" android:stretchMode="columnWidth" android:verticalSpacing="0dp" > </GridView> <WebView android:id="@+id/webview_fragment_main" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" /> </android.support.v4.widget.SwipeRefreshLayout> 

MainActivity – onCreate ():

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Const.DEBUGGING_INT) Log.d(Const.DEBUG, "Activity - onCreate"); prefs = PreferenceManager.getDefaultSharedPreferences(this); if (Const.DEBUGGING) Log.d(Const.DEBUG, "Index = " + index); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); toolbar = (Toolbar) findViewById(R.id.toolbar); spinner = (Spinner) toolbar.findViewById(R.id.spinner); mDrawerList = (ListView) findViewById(R.id.listview_drawer); setUpHeaderAndFooter(); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(""); setUpToolBar(); setUpSpinner(); setUpNavigationDrawer(); if ((findViewById(R.id.fragment_container) != null) && (findViewById(R.id.detail_fragment_container) != null)) { mTwoPane = true; } else { mTwoPane = false; } setFragment(prefs.getInt(Const.Prefs.MAININDEX, 0), 0); } 

Método setFragment en MainActivity:

 private void setFragment(int mainIndex, int subIndex) { if (Const.DEBUGGING_INT) { Log.d(Const.DEBUG, "Activity - setFragment"); Log.d(Const.DEBUG, "Position = " + mainIndex); Log.d(Const.DEBUG, "TwoPane? " + mTwoPane); } incrementClickCount(mainIndex); mMainFragment = new MainFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, mMainFragment).commit(); Bundle bundle = new Bundle(); bundle.putInt(Const.BundleParameters.MAININDEX, mainIndex); bundle.putInt(Const.BundleParameters.SUBINDEX, subIndex); bundle.putBoolean(Const.BundleParameters.TWOPANE, mTwoPane); bundle.putInt(Const.BundleParameters.CURRENTPOSITION, 0); mMainFragment.setParameters(bundle); mDrawerList.setItemChecked(mainIndex, true); mDrawerLayout.closeDrawer(mDrawerList); if (mTwoPane) { mDetailFragment = new DetailFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.detail_fragment_container, mDetailFragment) .commit(); if (Const.DEBUGGING) Log.d(Const.DEBUG, "URL = " + prefs.getString(Const.Prefs.CURRENT_URL, "")); Bundle b = new Bundle(); b.putString("url", prefs.getString(Const.Prefs.CURRENT_URL, "")); mDetailFragment.setParameters(b); } } 

MainFragment – onCreateView ():

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(Const.DEBUG, "Fragment - onCreateView"); View view = inflater.inflate(R.layout.fragment_main, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) view .findViewById(R.id.swipeRefreshLayout); mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.green, R.color.pink, R.color.yellow); // if (!mSwipeRefreshLayout.isRefreshing()) mSwipeRefreshLayout.setRefreshing(true); prefs = PreferenceManager.getDefaultSharedPreferences(activity); mDbAdapter = DatabaseHelper.get(getActivity().getApplicationContext()) .getDbAdapter(); gridview = (GridView) view.findViewById(R.id.gridview); webview = (WebView) view.findViewById(R.id.webview_fragment_main); webview.setWebViewClient(new MyWebViewClient()); webview.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { return super.onJsAlert(view, url, message, result); } }); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); webview.setVerticalScrollBarEnabled(false); webview.setHorizontalScrollBarEnabled(false); setTableDetails(); isTableEmpty = mDbAdapter.isTableEmpty(mTableName); if (isTableEmpty) { getDataFromServer(true); } else { checkRefreshTimeAndGetData(); } return view; } 

DetailFragment – onCreateView ():

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (Const.DEBUGGING) { Log.d(Const.DEBUG, "***** DetailFragment - onCreateView *****"); Log.d(Const.DEBUG, "URL = " + url); } View view = inflater .inflate(R.layout.fragment_detail, container, false); prefs = PreferenceManager.getDefaultSharedPreferences(activity); pd = (ProgressBar) view.findViewById(R.id.progressBar); webview = (WebView) view.findViewById(R.id.webview_fragment_detail); webview.setWebViewClient(new MyWebViewClient()); webview.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { return super.onJsAlert(view, url, message, result); } }); pd.setVisibility(View.VISIBLE); webview.setVisibility(View.GONE); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); webview.setVerticalScrollBarEnabled(false); webview.setHorizontalScrollBarEnabled(false); webview.loadUrl(url); // webview.loadDataWithBaseURL(url, null, "text/html", "utf-8", null); return view; } 

Logcat:

 11-16 23:15:05.234: E/FragmentManager(26609): No view found for id 0x7f0a0052 (com.xx.xxx:id/detail_fragment_container) for fragment DetailFragment{42476ab8 #1 id=0x7f0a0052} 

Entiendo que está buscando detail_fragment_container, que no tengo en modo retrato. ¿Cómo puedo solucionar esto? Déjeme saber si usted necesita el código también. Estará encantado de publicar ..

La única manera en que puedo pensar en que consigas ese error es que tu viejo diseño se usa. Eso podría ser porque super.onCreate(savedInstanceState);

En su lugar, intente ignorar el estado guardado:

 super.onCreate(null); 

Editar:

Respuesta al comentario de @matiash:

Dado que OP no proporcionó código para volver a crear el problema, es difícil probar otras soluciones (si las hay).

Sin embargo estoy de acuerdo en que restablecer el savedInstanceState es una especie de exceso. Por lo tanto, pienso OP debe probarlo él mismo y ver a que él guarda tantas vistas como sea posible.

Lo primero que viene a la mente es evitar que se salve la visión problemática:

 <FrameLayout android:id="@+id/detail_fragment_container" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="0.60" android:saveEnabled="false"/> 

El FragmentManager tratará de recrear todos los fragmentos cuando se rota, pero en modo vertical ya no tiene el diseño de DetailFragment , por lo que debe quitar el fragmento para evitar que se adjunte.

EDIT: Quizás la manera más limpia de detectar su cambio de orientación es usar el OrientationEventListener . Puede referirse a esta publicación y esto por algún ejemplo. Debe eliminar el fragmento dentro del método onOrientationChanged (int orientation) que debe anular.

Cambiar el código,

 if ((findViewById(R.id.fragment_container) != null) && (findViewById(R.id.detail_fragment_container) != null)) { mTwoPane = true; } else { mTwoPane = false; } 

por

 if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){ //Do some stuff mTwoPane = true; } else{ mTwoPane = false; } 

Espero que te ayude

  • Fragmentos anidados pierden llamadas a onCreateOptionsMenu después de rotación de pantalla
  • Evitar la actualización de la actividad en el cambio de orientación del fragmento android
  • Bloquear la orientación hasta que termine Asíntate
  • Fragmento manejo de la orientación de la pantalla con pestañas en barra de acción
  • ¿Tengo que usar el acelerómetro en Android para que mis fotos se orienten correctamente?
  • Problemas al manejar los cambios de orientación
  • IU distorsionada con Android
  • Emulador de panal invertido pantalla en retrato
  • El diálogo emergente de Spinner no ajusta su ancho en la rotación de la pantalla
  • Android: Detectar la orientación cambiada
  • Actividad sólo en retrato o en reverso
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.