Created
June 2, 2017 13:16
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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