Actividad del fragmento de inicio

Tengo una aplicación con muchos fragmentos, y estoy tratando de ir de un fragmento a otro cuando se hace clic en un botón.

La parte con la que estoy teniendo problemas es startActivity(new Intent(HomeFragment.this, FindPeopleFragment.class));

 package info.androidhive.slidingmenu; import info.androidhive.slidingmenu.HomeFragment; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.Toast; public class HomeFragment extends Fragment { public HomeFragment() { } ImageButton bSearchByLocation, bSearchByNumber; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View InputFragmentView = inflater.inflate(R.layout.fragment_home, container, false); bSearchByNumber = ((ImageButton) InputFragmentView .findViewById(R.id.bSearchByLocation)); bSearchByLocation = ((ImageButton) InputFragmentView .findViewById(R.id.bSearchByNumber)); bSearchByLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.bSearchByNumber) { Toast.makeText(getActivity(), "1", Toast.LENGTH_SHORT) .show(); startActivity(new Intent(HomeFragment.this, FindPeopleFragment.class)); } } }); bSearchByNumber.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.bSearchByLocation) { Toast.makeText(getActivity(), "2", Toast.LENGTH_SHORT) .show(); } } }); return InputFragmentView; } } 

después de hacer la solución el código se parece a esto:

 package info.androidhive.slidingmenu; import info.androidhive.slidingmenu.HomeFragment; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; public class HomeFragment extends Fragment { public HomeFragment() { } ImageButton bSearchByLocation, bSearchByNumber; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View InputFragmentView = inflater.inflate(R.layout.fragment_home, container, false); bSearchByNumber = ((ImageButton) InputFragmentView .findViewById(R.id.bSearchByLocation)); bSearchByLocation = ((ImageButton) InputFragmentView .findViewById(R.id.bSearchByNumber)); bSearchByLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.bSearchByNumber) { Toast.makeText(getActivity(), "1", Toast.LENGTH_SHORT) .show(); startActivity(new Intent(getActivity(), FindPeopleFragment.class)); } } }); bSearchByNumber.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.bSearchByLocation) { Toast.makeText(getActivity(), "2", Toast.LENGTH_SHORT) .show(); } } }); return InputFragmentView; } } 

pero cuando lo ejecuto, la aplicación se bloquea y se cierra. este es mi código androidmanifest:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="info.androidhive.slidingmenu" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="info.androidhive.slidingmenu.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="info.androidhive.slidingmenu.FindPeopleFragment"></activity> </application> </manifest> 

y este es mi logchat: introduzca la descripción de la imagen aquí

por cierto …. yo uso este código surce y trabajar en él: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer

En Fragment , debe obtener la actividad de alojamiento (el contexto) como getActivity() . Prueba esto en su lugar:

 startActivity(new Intent(getActivity(), FindPeopleFragment.class)); 

Declare la clase FindPeopleFragment en su manifiesto:

 <activity android:name="com.packagename.FindPeopleFragment" /> 

Todas las Activities (no Fragment ) deben declararse en su archivo de manifiesto.

Además, compruebe si FindPeopleFragment extiende Activity o FragmentActivity . Si esto extiende Fragment , no haga una Intent . Debes hacer una FragmentTransaction para reemplazar (o agregar arriba) tu fragmento antiguo (HomeFragment).


ACTUALIZAR

Usted está equivocado en el camino para lograr esto. Intentas iniciar una nueva Activity que, en tu caso, es un Fragment y no una actividad (extiende Fragmento) . Para lograr esto, usted puede:

 // call a method when click event ((MyFragmentActivity) getActivity()).replaceFragments(); 

Luego, dentro de su FragmentActivity , defina el método como:

 // replace the fragment container with this method public void replaceFragments() { Fragment newFragment = new FindPeopleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, newFragment); transaction.commit(); } 

UPDATE2

Como @Squonk dijo en comentario y también en su respuesta , mi respuesta anterior es una solución, pero no la correcta. Para tener una solución realmente adecuada , necesita declarar una Callback interface y asociar el Fragment con cualquier Activity .

Primero declare una interfaz y adjúntela a su actividad en su fragmento:

 OnFragSelected mCallback; public interface OnFragSelected { public void OnFragSelected(int id); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (OnFragSelected) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString()+" must implement OnFragSelected interface.."); } } 

Luego llame a esto en su evento de clic:

 @Override public void onClick(View v) { mCallback.OnFragSelected(800); } 

Finalmente, en su actividad de fragmento:

 ... implements HomeFragment.OnFragSelected { Fragment newFragment; @Override public void OnFragSelected(int id) { // example: id = 800 // ... newFragment = new FindPeopleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, newFragment); transaction.commit(); } } 

De esta manera "es más flexible […] Varias actividades ahora pueden incrustar su Fragmento, solo tienen que implementar la interfaz de comunicación" . Esto es importante porque "su fragmento es reutilizable y por lo tanto no dependen de esa actividad específica " . Además, si "usa el fragmento en otro lugar, erradica el riesgo de una RuntimeException porque está fuertemente mecanografiada".

Esta pregunta y estas respuestas sobre fragmento 2 fragmento de comunicación puede mostrar la diferencia. Aquí , usted tiene el ejemplo de google y esta respuesta: onAttach devolución de llamada de un fragmento a la actividad podría usted averiguarlo.

Haga esto a su intención:

 startActivity(new Intent(getActivity(), FindPeopleFragment.class)); 

y agrega esto a tu manifiesto:

 <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="info.androidhive.slidingmenu.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.yourpackagename.FindPeopleFragment"></activity> </application> 

Añada su actividad a su manifiesto dentro de la etiqueta de aplicaciones.

Debería funcionar ahora

Un Fragment debe ser modular, autónomo y reutilizable – no debería conocer otros componentes de la aplicación.

No inicie una Activity directamente desde un Fragment . En su lugar, debe declarar una interfaz que implementa su Activity principal. Al hacer clic en un botón de su Fragment , debe hacer una llamada a un método en la interfaz indicando a la Activity principal qué botón ha sido presionado. La Activity principal puede iniciar la Activity se necesita.

Consulte Creación de devoluciones de llamada de eventos

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.