繁体   English   中英

将值从活动传递到片段android

[英]Passing values from activity to fragment android

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

主要活动:-

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

我该如何解决这个问题?

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

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

你可以这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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