Button Listener para el botón en el fragmento en android

Soy nuevo en Android y estoy tratando de aprender por mi cuenta. Pero estoy teniendo un momento difícil con Fragmentos. Estoy creando una aplicación simple para aprender fragmentos. Creo que puede parecer tonto, pero realmente no puedo conseguir que esto funcione.

Todo lo que quiero hacer es en el clic de un botón (buttonSayHi) en Fragment_One, Fragment_One debe ser reemplazado por Fragment_Two.

No estoy seguro de cuándo se llama el código Fragment y dónde se supone que debo escribir mi código para llamar al segundo fragmento. Tengo el error: No puedo iniciar el componente Activity.

Sin embargo, el código funciona bien si descarto el oyente para el botón y el fragmento se muestra dentro de la actividad.

He hecho una investigación considerable, leer el tutorial de fragmentos en developer.android.com y también el tutorial de Lars Vogella. Creo que mis conceptos no son claros.

Cualquier ayuda será apreciada.

El siguiente es el código:

Activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/frameLayoutFragmentContainer" android:layout_width="fill_parent" android:layout_height="fill_parent" > </FrameLayout> 

Fragment_one.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/editTextPersonName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" > <requestFocus /> </EditText> <Button android:id="@+id/buttonSayHi" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Say Hi" android:onClick="onButtonClicked"/> </LinearLayout> 

Fragment_two.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textViewResult" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="I will say Hi!" /> </LinearLayout> 

MainActivity.java

 package com.example.fragmenttutorial; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; public class MainActivity extends Activity{ View view; FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Fragment fragmentOne = new FragmentOne(); fragmentTransaction.add(R.id.frameLayoutFragmentContainer, fragmentOne); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } protected void onButtonClicked() { if(view.getId() == R.id.buttonSayHi){ Fragment fragmentTwo = new FragmentTwo(); fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } } 

FragmentOne.java

 package com.example.fragmenttutorial; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentOne extends Fragment{ View view; FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one, container, false); return view; } // protected void onButtonClicked() // { // if(view.getId() == R.id.buttonSayHi){ // Fragment fragmentTwo = new FragmentTwo(); // // fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo); // fragmentTransaction.addToBackStack(null); // // fragmentTransaction.commit(); // // } // // } } 

He comentado el código de clic en el fragmento. También he intentado implementar onClickListener en el fragmento.

FragmentTwo.java

 package com.example.fragmenttutorial; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentTwo extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_two, container, false); return view; } } 

EDIT: He eliminado la línea android: onClick = "onButtonClicked" de mi código en XML. Y editado los siguientes archivos, pero todavía no funciona. ¿Pueden ustedes proporcionarme un ejemplo de trabajo sin la línea android: onClick = "onButtonClicked".

MainActivity.java

 package com.example.fragmenttutorial; import android.os.Bundle; import android.view.View; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; public class MainActivity extends Activity{ View view; Fragment fragmentOne; FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentOne = new FragmentOne(); fragmentTransaction.add(R.id.frameLayoutFragmentContainer, fragmentOne); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } 

FragmentOne.java

 package com.example.fragmenttutorial; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; public class FragmentOne extends Fragment implements OnClickListener{ View view; Fragment fragmentTwo; FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one, container, false); Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi); buttonSayHi.setOnClickListener(this); return view; } @Override public void onClick(View v) { fragmentTwo = new FragmentTwo(); fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } 

Gracias por sus valiosas sugerencias.

Su clase de fragmento debe implementar OnClickListener

 public class SmartTvControllerFragment extends Fragment implements View.OnClickListener 

Entonces consiga la visión, el botón del acoplamiento y fije onClickListener como en el ejemplo abajo

  View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.smart_tv_controller_fragment, container, false); upButton = (Button) view.findViewById(R.id.smart_tv_controller_framgment_up_button); upButton.setOnClickListener(this); return view; } 

A continuación, agregue el método onClickListener y haga lo que quiera.

 @Override public void onClick(View v) { //do what you want to do when button is clicked switch (v.getId()) { case R.id.textView_help: switchFragment(HelpFragment.TAG); break; case R.id.textView_settings: switchFragment(SettingsFragment.TAG); break; } } 

Este es mi ejemplo de código, pero espero que hayas entendido

Usa tu código

 public class FragmentOne extends Fragment implements OnClickListener{ View view; Fragment fragmentTwo; FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one, container, false); Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi); buttonSayHi.setOnClickListener(this); return view; } 

Pero creo que es mejor manejar los botones de esta manera:

 @Override public void onClick(View v) { switch(v.getId()){ case R.id.buttonSayHi: /** Do things you need to.. fragmentTwo = new FragmentTwo(); fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); */ break; } } 

Escuchador de fragmentos

Si un fragment necesita comunicar events a la activity , el fragment debe definir una interface como un tipo interno y requiere que la activity debe implement esta interface :

 import android.support.v4.app.Fragment; public class MyListFragment extends Fragment { // ... // Define the listener of the interface type // listener is the activity itself private OnItemSelectedListener listener; // Define the events that the fragment will use to communicate public interface OnItemSelectedListener { public void onRssItemSelected(String link); } // Store the listener (activity) that will have events fired once the fragment is attached @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof OnItemSelectedListener) { listener = (OnItemSelectedListener) activity; } else { throw new ClassCastException(activity.toString() + " must implement MyListFragment.OnItemSelectedListener"); } } // Now we can fire the event when the user selects something in the fragment public void onSomeClick(View v) { listener.onRssItemSelected("some link"); } } 

Y luego en la activity :

 import android.support.v4.app.FragmentActivity; public class RssfeedActivity extends FragmentActivity implements MyListFragment.OnItemSelectedListener { DetailFragment fragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rssfeed); fragment = (DetailFragment) getSupportFragmentManager() .findFragmentById(R.id.detailFragment); } // Now we can define the action to take in the activity when the fragment event fires @Override public void onRssItemSelected(String link) { if (fragment != null && fragment.isInLayout()) { fragment.setText(link); } } } 

Mientras que usted está declarando onclick en XML, entonces debe método declair y pasar View v como parámetro y hacer que el método público …

 Ex: //in xml android:onClick="onButtonClicked" // in java file public void onButtonClicked(View v) { //your code here } 
  //sure run it i will also test it //we make a class that extends with the fragment public class Example_3_1 extends Fragment implements OnClickListener { View vi; EditText t; EditText t1; Button bu; // that are by defult function of fragment extend class @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,BundlesavedInstanceState) { vi=inflater.inflate(R.layout.example_3_1, container, false);// load the xml file bu=(Button) vi.findViewById(R.id.button1);// get button id from example_3_1 xml file bu.setOnClickListener(this); //on button appay click listner t=(EditText) vi.findViewById(R.id.editText1);// id get from example_3_1 xml file t1=(EditText) vi.findViewById(R.id.editText2); return vi; // return the view object,that set the xml file example_3_1 xml file } @Override public void onClick(View v)//on button click that called { switch(v.getId())// on run time get id what button os click and get id { case R.id.button1: // it mean if button1 click then this work t.setText("UMTien"); //set text t1.setText("programming"); break; } } } 

Prueba esto :

FragmentOne.java

 import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class FragmentOne extends Fragment{ View rootView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_one, container, false); Button button = (Button) rootView.findViewById(R.id.buttonSayHi); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onButtonClicked(v); } }); return rootView; } public void onButtonClicked(View view) { //do your stuff here.. final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frameLayoutFragmentContainer, new FragmentTwo(), "NewFragmentTag"); ft.commit(); ft.addToBackStack(null); } } 

Compruebe esto: haga clic aquí

Esto funciona para mí.

 private OnClickListener mDisconnectListener; mDisconnectListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }; ... ... onCreateView(...){ mButtonDisconnect = (Button) rootView.findViewById(R.id.button_disconnect); mButtonDisconnect.setOnClickListener(mDisconnectListener); ... } 

Sólo tienes que obtener la vista de la actividad que llevan este fragmento y esto sólo podría suceder cuando su fragmento ya está creado

onViewCreated() método onViewCreated() dentro de tu fragmento y disfruta de su magia 🙂 ..

 @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Button button = (Button) view.findViewById(R.id.YOURBUTTONID); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //place your action here } }); 

Espero que esto pueda ayudarte ;

Simplemente pase el objeto de vista en la función onButtonClicked. GetView () no parece funcionar como se esperaba en el fragmento. Prueba este código para tu fragmento FragmentOne

PD. Ha redefinido la vista de objeto en su código FragmentOne original.

 package com.example.fragmenttutorial; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentOne extends Fragment{ FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one, container, false); onButtonClicked(view); return view; } protected void onButtonClicked(View view) { if(view.getId() == R.id.buttonSayHi){ Fragment fragmentTwo = new FragmentTwo(); fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } 
  • Configuración de la aplicación: layout_behavior mediante programación
  • Problemas con Android Fragment pila trasera
  • Conservar estado de fragmento entre actividades
  • Cómo abrir la página de fragmentos, cuando se presiona una notificación en android
  • cómo acceder al botón del fragmento A del fragmento B
  • Android Fragment Pager y el indicador de página personalizada (ViewPagerIndicator creado por Jake Wharton)
  • Android FragmentTabHost - ¿Todavía no está completamente horneado?
  • Siempre use v4 Fragments en lugar de la build-in android.app.Fragment?
  • Gestión de Fragmentos
  • Error al inflacionar la clase com.google.android.youtube.player.YouTubePlayerView
  • Android Drawer Layout está mostrando contenido de fragmentos
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.