I have two fragments and I want to show them in my screen one by one. They are managed by MainActivity. The first fragment contains a TextView and a Button. The second fragment contains an EditText and a Button. What I am trying to do is: The first fragment shows on screen, and when the user press the button I want my activity to show the second fragment, and when the user press the button from this fragment I want to send the text from the EditText to the first fragment and display it on the TextView. I used interface for listeners.
public class MainActivity extends AppCompatActivity implements Listener, ListenerTwo{
FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentPlaceholder, new FragmentOne());
fragmentTransaction.commit();
}
@Override
public void onButtonSelected() {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentPlaceholder, new FragmentTwo());
fragmentTransaction.commit();
}
@Override
public void onButtonPressed(String text) {
FragmentOne fragmentOne = (FragmentOne)getSupportFragmentManager().findFragmentById(R.id.fragmentPlaceholder);
if (fragmentOne != null)
fragmentOne.setTextt(text);
}
}
In my FragmentOne:
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button button = view.findViewById(R.id.button);
textView = view.findViewById(R.id.textView);
Listener listener = (Listener) getActivity();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "button clicked", Toast.LENGTH_SHORT).show();
if (listener != null)
listener.onButtonSelected();
}
});
}
public void setTextt (String text) {
textView.setText(text);
}
In FragmentTwo:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button button = view.findViewById(R.id.button2);
EditText editText = view.findViewById(R.id.editText);
ListenerTwo listener = (ListenerTwo) getActivity();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "button clicked", Toast.LENGTH_SHORT).show();
if (listener != null)
listener.onButtonPressed(editText.getText().toString());
}
});
}