Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should probably try to decouple the fragment from the activity in case you want to use it somewhere else. You can do this by creating a interface that your activity implements. </p> <p>So you would define an interface like the following:</p> <p>Suppose for example you wanted to give the activity a String and have it return a Integer:</p> <pre><code>public interface MyStringListener{ public Integer computeSomething(String myString); } </code></pre> <p>This can be defined in the fragment or a separate file. </p> <p>Then you would have your activity implement the interface. </p> <pre><code>public class MyActivity extends FragmentActivity implements MyStringListener{ @Override public Integer computeSomething(String myString){ /** Do something with the string and return your Integer instead of 0 **/ return 0; } } </code></pre> <p>Then in your fragment you would have a MyStringListener variable and you would set the listener in fragment onAttach(Activity activity) method. </p> <pre><code>public class MyFragment { private MyStringListener listener; @Override public void onAttach(Context context) { super.onAttach(context); try { listener = (MyStringListener) context; } catch (ClassCastException castException) { /** The activity does not implement the listener. */ } } } </code></pre> <p>edit(17.12.2015):<code>onAttach(Activity activity) is deprecated, use onAttach(Context context) instead, it works as intended</code></p> <p>The first answer definitely works but it couples your current fragment with the host activity. Its good practice to keep the fragment decoupled from the host activity in case you want to use it in another acitivity. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload