将值从活动传递到片段android

时间:2014-01-09 07:07:54

标签: java android android-fragments

我想将活动中的某些值传递给android中的片段。 这是一些代码: -

MainActivity: -

PlaceDialogFragment dialogFragment = new PlaceDialogFragment(place,dm);

片段: -

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

在片段中使用构造函数会给我一个错误: -

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

如果我用以下代码替换构造函数: -

  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 ;
}

我在MainActivity.Java中收到错误: -

The constructor PlaceDialogFragment(Place, DisplayMetrics) is undefined

我如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您可以这样做:

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);

并在Fragment onCreateView方法中:

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