如下操作:
片段A
public class FragmentA extends Fragment implements View.OnClickListener {
OnButtonPressed mCallback;
Button yourButton;
TextView textViewFragA;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_layout, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
yourButton = findViewById(R.id.yourBtn);
textViewFragA = findViewById(R.id.textViewFragA);
yourButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.yourBtn:
mCallback.onButtonPressed(textViewFragA);
break;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnButtonPressed) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnButtonPressed");
}
}
@Override
public void onDetach() {
mCallback = null; // Avoid memory leaking
super.onDetach();
}
/**
* Interface called whenever the user has clicked on the Button
* @param textView The TextView to add in FragmentB
*/
public interface OnButtonPressed{
void onButtonPressed(TextView textView);
}
}
FragmentB
public class FragmentB extends Fragment{
TextView textViewFragB;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_layout, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textViewFragB= findViewById(R.id.textViewFragB);
}
public TextView getTextViewFragB(){
return textViewFragB;
}
活動
public class TabControllerActivity extends AppCompatActivity implements FragmentA.OnButtonPressed{
MyAdapter adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// Your Stuff
}
// Everytime the user clicks on the Button in FragmentA, this interface method gets triggered
@Override
public void onButtonPressed(TextView textViewFragA) {
FragmentB fragmentB = (FragmentB) adapter.getItem(1)/* Be careful here and get the right fragment,
otherwise the App will crash*/
// Since you got the TextView and not only the text inside of it,
// you can do whatever you want. Here for example we set the text like the textViewFragA.
//In a few words you turn the textViewFragB to the other one
fragmentB.getTextViewFragB().setText(textViewFragA.getText().toString());
}
}
希望這將有助於
使用廣播接收器@Shures –