[英]Passing values from activity to fragment android
I want to pass certain values from an activity to a fragment in android. 我想将某个值从活动传递到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 :- 我在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: 并在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.