Android Fragment Interaction

I have 1 activity with 2 fragments in an android app. On the first fragment, I pressed the (btnA) button. On the second, I hit TextView (txtB).

How can I set the text in the TextView of the second fragment by clicking on the button in the first action?

Thanks, I'm new to Android app development.

Joskxp

+2
source share
2 answers

Ok, you could do something like this:

In your activity, indicate public links to both of your fragments:

public FragmentNumberOne getFragmentOne() { return fragOne; } public FragmentNumberTwo getFragmentTwo() { return fragTwo; } 

then provide accessors for the TextView in the Fragment class of fragment one:

 public TextView getTextView() { return mTextView; } 

and in the original Fragment you can use:

 ((MyActivity)getActivity()).getFragmentOne().getTextView().setText("Hello"); 
+2
source

In accordance with Android best practices described here .

This is a bit more detailed than Graeme's solution, but allow reuse of your snippets. (You can use FragmentWithButton on another screen, and the button can do something else)

You have two fragments ( FragmentWithButton and FragmentWithText ) and one action ( MyActivity )

  • Create the FragmentWithButtonHost interface in the FragmentWithButton :

     public class FragmentWithButton extends Fragment { FragmentWithButtonHost host; public interface FragmentWithButtonHost{ public void onMyButtonClicked(View v); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { host = (FragmentWithButtonHost) activity; } catch (ClassCastException e) { // TODO Handle exception } } /** * Click handler for MyButton */ public void onMyButtonClick(View v) { host.onMyButtonClicked(v); } } 
  • Create a public FragmentWithText method to set the text from the action:

     public class FragmentWithText extends Fragment{ ... public void setText(String text) { // Set text displayed on the fragment } } 
  • Make sure your activity implements the FragmentWithButtonHost interface and calls the setText method:

     public MyActivity implements FragmentWithButtonHost { ... @Override public void onMyButtonClicked(View v) { getFragmentWithText().setText("TEST"); } public FragmentWithText getFragmentWithText() { // Helper method to get current instance of FragmentWithText, // or create a new one if there isn't any } } 
+2
source

Source: https://habr.com/ru/post/1201370/


All Articles