如何将片段中的非默认构造函数更改为默认构造函数?

时间:2012-11-21 03:12:44

标签: java android

代码:

public PlacePickerFragment() {
    this(null);
}
public PlacePickerFragment(Bundle args) {
    super(GraphPlace.class, R.layout.com_facebook_placepickerfragment, args);
    setPlacePickerSettingsFromBundle(args);
}

您好,我想从上面的代码中删除弃用警告,有没有办法将其更改为默认构造函数?

3 个答案:

答案 0 :(得分:6)

创建片段时,请使用setArgument():

Bundle args = new Bundle();
// Construct your bundle here
Fragment mFragment = new PlacePickerFragment();
mFragment.setArguments(args);
mFragment.initialize();

并使用fragment的默认构造函数。设置参数后,可能需要调用setPlacePickerSettingsFromBundle(),如下所示:

public PlacePickerFragment() {
    super(GraphPlace.class, R.layout.com_facebook_placepickerfragment, args);
}

public void initialize() {
    Bundle args = getArguments();
    setPlacePickerSettingsFromBundle(args);
}

答案 1 :(得分:1)

删除Bundle参数并使构造函数不带参数。然后使用setArguments()传递捆绑包。如有必要,创建静态工厂方法以使用必要的参数创建片段。

答案 2 :(得分:0)

Lawrence Choy的回答非常有用,但是对我来说没有用,因为super()调用不接受args变量。这对我有用:

public void initialize() {
  Bundle args = getArguments();
  setPlacePickerSettingsFromBundle(args);
}

/**
  * Default constructor. Creates a Fragment with all default properties.
  */
public PlacePickerFragment() {
  super(GraphPlace.class, R.layout.com_facebook_placepickerfragment, null);
}