FirstFragment.java
public class FirstFragment extends Fragment { Button buttonSend; EditText editTextName; private OnFragment1InteractionListener mListener; public FirstFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view= inflater.inflate(R.layout.fragment_first, container, false); buttonSend= (Button) view.findViewById(R.id.buttonSend); editTextName= (EditText) view.findViewById(R.id.editTextName); buttonSend.setOnClickListener(onClickListener); return view; } View.OnClickListener onClickListener=new View.OnClickListener() { @Override public void onClick(View v) { String name=editTextName.getText().toString(); onButtonPressed(name); } }; public void onButtonPressed(String name) { if (mListener != null) { mListener.onFragment1ButtonClicked(name); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragment1InteractionListener) { mListener = (OnFragment1InteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragment1InteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragment1InteractionListener { void onFragment1ButtonClicked(String name); } }
SecondFragment.java
public class SecondFragment extends Fragment { TextView textViewMessage; public SecondFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view= inflater.inflate(R.layout.fragment_second, container, false); textViewMessage= (TextView) view.findViewById(R.id.textViewMessage); return view; } public void setTextViewMessage(String name) { textViewMessage.setText("Hello " + name); } }
MainActivity.java
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFragment1InteractionListener{ RelativeLayout container1; RelativeLayout container2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); container1= (RelativeLayout) findViewById(R.id.relativeLayoutContainer1); container2= (RelativeLayout) findViewById(R.id.relativeLayoutContainer2); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); FirstFragment firstFragment=new FirstFragment(); SecondFragment secondFragment=new SecondFragment(); transaction.add(R.id.relativeLayoutContainer1,firstFragment); transaction.add(R.id.relativeLayoutContainer2,secondFragment); transaction.commit(); } @Override public void onFragment1ButtonClicked(String name) { SecondFragment fragment= (SecondFragment) getSupportFragmentManager().findFragmentById(R.id.relativeLayoutContainer2); fragment.setTextViewMessage(name); } }
References
https://github.com/mhdr/AndroidSamples/tree/master/032