Android Fragment Activity Communication
ChangeColorFragment.java
public class ChangeColorFragment extends Fragment { private OnChangeColorFragmentInteractionListener mListener; RadioGroup radioGroupColors; public ChangeColorFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view= inflater.inflate(R.layout.fragment_change_color, container, false); radioGroupColors= (RadioGroup) view.findViewById(R.id.radioGroupColors); radioGroupColors.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { onColorChanged(checkedId); } }); return view; } public void onColorChanged(int id) { if (mListener != null) { mListener.onChangeColorFragmentInteraction(id); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnChangeColorFragmentInteractionListener) { mListener = (OnChangeColorFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnChangeColorFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnChangeColorFragmentInteractionListener { void onChangeColorFragmentInteraction(int id); } }
MainActivity.java
public class MainActivity extends AppCompatActivity implements ChangeColorFragment.OnChangeColorFragmentInteractionListener{ RelativeLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout= (RelativeLayout) findViewById(R.id.activity_main); FragmentTransaction transaction= getSupportFragmentManager().beginTransaction(); ChangeColorFragment changeColorFragment=new ChangeColorFragment(); transaction.add(R.id.relativeLayoutFragmentContainer,changeColorFragment); transaction.commit(); } @Override public void onChangeColorFragmentInteraction(int id) { switch (id) { case R.id.radioButtonRed: layout.setBackgroundColor(getResources().getColor(R.color.red)); break; case R.id.radioButtonBlue: layout.setBackgroundColor(getResources().getColor(R.color.blue)); break; } } }
References
https://github.com/mhdr/AndroidSamples/tree/master/031