Use Fragment.setarguments (bundle bundle) to pass parameters instead of constructors

Source: Internet
Author: User

Google's official recommendation is to use setargument to send arguments instead of using constructors.

Because the fragment will call its own parameterless constructor when switching the screen, the arguments in the constructor will be invalidated.

public class Framenttestactivity extends Actionbaractivity {


protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_main);

After switching the screen after the savedinstancestate is not NULL, so only the first time in the call, if not judged, switch the screen will be in the original fragment on the basis of a new fragment, so that there are 2 fragment overlap.

if (savedinstancestate = = null) {

Getsupportfragmentmanager (). BeginTransaction ()

. Add (, New testfragment ("param")). commit ();



public static class Testfragment extends Fragment {

Private String MArg = "Non-param";

Public Testfragment () {

LOG.I ("INFO", "Testfragment Non-parameter constructor");


Public testfragment (String Arg) {

MARG = arg;

LOG.I ("INFO", "testfragment construct with parameter");



Public View Oncreateview (layoutinflater inflater, ViewGroup container,

Bundle savedinstancestate) {

View Rootview = inflater.inflate (R.layout.fragment_main, container,


TextView TV = (TextView) Rootview.findviewbyid (;

Tv.settext (MARG);

return rootview;




Use Fragment.setarguments (bundle bundle) to pass parameters instead of constructors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.