问题
I have 1 activity with 2 fragments in an Android app. On the first fragment, I did put a button (btnA). On the second I putt a TextView (txtB).
How can I set a Text in the TextView of the second fragment by pushing on the button on the first activity?
Thx, I'm new to android app development
JoskXP
回答1:
Well you could do something like this:
In your activity, provide public links to both of your fragments:
public FragmentNumberOne getFragmentOne() {
return fragOne;
}
public FragmentNumberTwo getFragmentTwo() {
return fragTwo;
}
then provide accessors to the TextView in the Fragment class of fragment one:
public TextView getTextView() {
return mTextView;
}
and in your original Fragment you can then use:
((MyActivity)getActivity()).getFragmentOne().getTextView().setText("Hello");
回答2:
Following Android best practice described here.
This is slightly more verbose than the solution of Graeme, but allow reuse of your fragments. (You could use FragmentWithButton in another screen, and the button could do something different)
You have two Fragments (FragmentWithButton and FragmentWithText) and one activity (MyActivity)
Create an interface
FragmentWithButtonHostinFragmentWithButton: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 method in
FragmentWithTextto set the text from the activity:public class FragmentWithText extends Fragment{ ... public void setText(String text) { // Set text displayed on the fragment } }Make sure your activity implements the
FragmentWithButtonHostinterface, and call thesetTextmethod: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 } }
来源:https://stackoverflow.com/questions/14705359/how-to-set-a-text-in-the-textview-of-the-second-fragment-by-pushing-on-the-butto