Android: ¿cómo puedo acceder a las vistas (utilizando findViewById) de una actividad de un fragmento onCreateView ()?

Tengo un proyecto bastante simple con una actividad que contiene un fragmento. Lo único que puede no estar familiarizado con es que estoy usando un VideoEnabledWebView que no es tan complicado y es algo que he utilizado antes. Es solo una vista web personalizada.

Aquí está mi código:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> 

 <!-- Don't forget the internet permission if you will be using the WebView to load remote content --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:hardwareAccelerated="true" > <!-- Only works in API level 11+, and allows the HTML5 videos to play in-line --> <activity android:name="name.cpr.ExampleActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> 

EjemploActividad.java

 import android.app.Activity; import android.os.Bundle; import android.util.Log; import cpr.name.videoenabledwebview.R; public class ExampleActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { Log.i("rai", "activity onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); } } 

activity_example.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ExampleActivity"> <!-- View that will be hidden when video goes fullscreen --> <RelativeLayout android:id="@+id/nonVideoLayout" android:layout_width="match_parent" android:layout_height="match_parent" > <fragment android:name="name.cpr.WebViewFragment" android:id="@+id/webViewFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> <!-- View where the video will be shown when video goes fullscreen --> <RelativeLayout android:id="@+id/videoLayout" android:layout_width="match_parent" android:layout_height="match_parent" > </RelativeLayout> 

WebViewFragment.java

 package name.cpr; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import cpr.name.videoenabledwebview.R; public class WebViewFragment extends Fragment { private VideoEnabledWebView webView; private VideoEnabledWebChromeClient webChromeClient; View rootView; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.root, container, false); webView = (VideoEnabledWebView) rootView.findViewById(R.id.webView); Log.i("rai", "nonVideoLayout = " + R.id.nonVideoLayout); Log.i("rai", "videoLayout = " + R.id.videoLayout); View nonVideoLayout = rootView.findViewById(R.id.nonVideoLayout); if(nonVideoLayout == null){ Log.i("rai", "why is nonVideoLayout null?"); } ViewGroup videoLayout = (ViewGroup) rootView.findViewById(R.id.videoLayout); if(videoLayout == null){ Log.i("rai", "why is videoLayout null?"); } webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout); webView.setWebChromeClient(webChromeClient); webView.loadUrl("http://m.youtube.com"); return rootView; } } 

root.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="100dp" android:layout_height="100dp" android:text="the fragment"/> <name.cpr.VideoEnabledWebView android:id="@+id/webView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> 

Simplemente no puedo tener acceso a esos dos diseños relativos en mi actividad, sigo recibiendo null.

Cosas que he intentado que NO funcionan:

rootView.findViewById // rootView es el retorno del inflar

getActivity (). findViewById

getView (). findViewById

container.findViewById

También he intentado esto en mis fragmentos onCreate:

 context = getActivity().getApplicationContext(); webViewFragmentId = context.getResources().getIdentifier( "root", "layout", context.getPackageName()); webViewId = context.getResources().getIdentifier("webView", "id", context.getPackageName()); nonVideoLayoutId = context.getResources().getIdentifier("nonVideoLayout", "id", context.getPackageName()); videoLayoutId = context.getResources().getIdentifier("videoLayout","id", context.getPackageName()); rootView = inflater.inflate(webViewFragmentId, null); webView = (VideoEnabledWebView) rootView.findViewById(webViewId); View nonVideoLayout = getActivity().findViewById(nonVideoLayoutId); ViewGroup videoLayout = (ViewGroup) getActivity().findViewById(videoLayoutId); webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout); webView.setWebChromeClient(webChromeClient); webView.loadUrl("http://m.youtube.com"); return rootView; 

Debe anular onActivityCreated y acceder a las vistas que necesita de la actividad en ese método porque cuando onCreateView se ejecuta en el fragmento de la actividad aún no ha tenido su conjunto de diseño por lo que no puede acceder a sus vistas.

 @Override public void onActivityCreated (Bundle savedInstanceState) { View nonVideoLayout = getActivity().findViewById(R.id.nonVideoLayout); ViewGroup videoLayout = (ViewGroup) getActivity().findViewById(R.id.videoLayout); ... } 

Necesita anular onActivityCreated () como la vista de actividad no se crea hasta que este método se llama.

 @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); View nonVideoLayout = ((MainActivity)getActivity()).findViewById(R.id.nonVideoLayout); if(nonVideoLayout == null){ Log.e("rai", "why is nonVideoLayout null?"); } else{ Log.e("rai", "view not null hurray"); } View videoLayout = getActivity().findViewById(R.id.videoLayout); if(videoLayout == null){ Log.e("rai", "why is videoLayout null?"); }else{ Log.e("rai", "view not null hurray"); } 

Necesitas anular onViewCreated. Las vistas no se crean en el onCreate pero son una vez que la vista realmente se crea. Esta publicación da un poco más de información Diferencia entre onCreateView y onViewCreated en Fragmento

 @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ... } 
  • La mejor manera de evitar pérdidas de memoria en el fragmento android
  • Android: error con la interacción de fragmentos Interesante
  • La aplicación de Android se bloquea después de un tiempo utilizando Fragments y ViewPager
  • Refreshing ArrayAdapter onResume
  • Cambiar el diseño mientras cambia la orientación en tiempo de ejecución en un fragmento sin volver a crear la vista
  • Fragmentos anidados animados de Android
  • La tecla de retroceso para hacer estallar el fragmento muestra los fragmentos superpuestos
  • La mejor práctica para manejar el cambio de orientación: Android
  • ¿Cómo funciona `onViewStateRestored` de Fragments?
  • Devolución de llamada a notifyDataSetChanged
  • Botón Butterknife Fragment no funciona
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.