Skip to content

Instantly share code, notes, and snippets.

@NoelOmo
Created June 2, 2017 13:16
Show Gist options
  • Save NoelOmo/819b0fdcfbef1f08a55ebdaaf24d333a to your computer and use it in GitHub Desktop.
Save NoelOmo/819b0fdcfbef1f08a55ebdaaf24d333a to your computer and use it in GitHub Desktop.
Gist to send data to a fragment from an activity using the newInstance method
public class AddActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openFragmentA(/*Pass your eight strings*/);
}
}
public void openFragmentA(/*eight Strings*/){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
FragmentA myFragment = FragmentA.newInstance(/*eight Strings*/);
ft.replace(R.id.your_placeholder, myFragment);
ft.commit();
}
public class FragmentA extends Fragment {
public static FragmentA newInstance(String a, String b, ...)
{
FragmentA myFragment = new FragmentA();
Bundle args = new Bundle();
//Do the same for all the strings you want to pass
args.putInt("StringA", a);
args.putInt("StringB", b);
myFragment.setArguments(args);
return myFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
//Get the arguements you passed from the newinstance method
getArguments().getInt("StringA", "DefaultValue");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment