简体   繁体   中英

Passing values from activity to fragment android

I want to pass certain values from an activity to a fragment in android. Here is some code:-

MainActivity:-

PlaceDialogFragment dialogFragment = new PlaceDialogFragment(place,dm);

Fragment:-

 public PlaceDialogFragment(Place place, DisplayMetrics dm){
        super();
        this.mPlace = place;
        this.mMetrics = dm;
    }

Using a constructor in the fragment gives me an error:-

Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead

If i replace the constructor with:-

  public static final DialogFragment newInstance(Place place, DisplayMetrics dm)
{
    DialogFragment fragment = new DialogFragment();
    Bundle bundle = new Bundle(2);
    bundle.putParcelable("Place", place);
    bundle.putFloat("Metrics", dm.density);
    fragment.setArguments(bundle);
    return fragment ;
}

I get an error in the MainActivity.Java :-

The constructor PlaceDialogFragment(Place, DisplayMetrics) is undefined

How do i resolve this?

更改您的活动以使用新方法。

PlaceDialogFragment dialogFragment = PlaceDialogFragment.newInstance(place, dm);

You can do this in this manner:

From Activity you send data with intent as:

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM