Skip to content

Instantly share code, notes, and snippets.

@cutiko
Created March 30, 2018 00:50
Show Gist options
  • Save cutiko/d50b0ccca96fc36171ca6c7c95ca2301 to your computer and use it in GitHub Desktop.
Save cutiko/d50b0ccca96fc36171ca6c7c95ca2301 to your computer and use it in GitHub Desktop.
Comunicar Fragment con Activity

1.- Crea una interface con un método adentro, los argumentos del metodo son los que se van a pasar ascendentemente

2.- Esa interface implementala en la activity anfitriona

3.- En el fragment crea una variable de campo que sea la interface

4.- En el fragment sobreescribe onattach

5.- dentro de onattach di que el context es igual a tu interface, vas a tener que castear

6.- cómo tu interface es una variable de campo, la puedes usar en cualquier lado del fragment

7.- Entonces dices theNameOfYourInterface.yourMethod(someArgument) en el fragment

8.- Y eso va a ocurrir en la activity

9.- Dentro del método que se implementó en la activity, recibe el parámetro y haz algo

public class HostActivity extends AppCompatActivity implements TheInterface {
//TODO skipping other methods for simplicity
@Override
public void innerInterfaceMethod(String example) {
//That string is from the Fragment, get it and do anything with it
}
}
public class NormalFragment extends Fragment {
private TheInterface communicator;
//This is part of the fragment lifecycle
@Overrida
onAttach(Context context) {
super.onAttach(context);
communicator = (TheInterface) context;
//No you can use the interface as ascending communition wherever you want
}
}
public interface TheInterface {
void innerInterfaceMethod(String example);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment