将int从活动传递到片段

时间:2014-12-08 15:07:06

标签: android android-fragments

我在我的活动中使用以下代码:

public class SongSing extends Activity实现了SongCommunicator {

int lang, level;
static SongFragment2 fragment2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Bundle extras = getIntent().getExtras();
    lang = extras.getInt("lang");
    level = extras.getInt("level");

    Bundle b = new Bundle();
    b.putInt("lang", lang);
    Fragment f = new Fragment();
    f.setArguments(b);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_song_sing);

}

和我的片段:

公共类SongFragment1扩展Fragment实现AdapterView.OnItemClickListener {

int lang, level;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.song_fragment1, null);

}

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);

    Bundle bundle = this.getArguments();
    if(bundle != null){
        lang = bundle.getInt("lang");
    }

但我得到一个空包。

任何想法为什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

创建片段的常见模式如下所示:

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param broadcast to watch
 * @return A new instance of fragment LivePlayerFragment.
 */
public static LivePlayerFragment newInstance(Broadcast broadcast) {
    LivePlayerFragment fragment = new LivePlayerFragment();
    Bundle args = new Bundle();
    args.putParcelable(PARAM_BROADCAST, broadcast);
    fragment.setArguments(args);
    return fragment;
}

public LivePlayerFragment() {
    // Required empty public constructor
}

如您所见,您有一个Static方法来使用适当的参数构建片段。注意空构造函数。这对于片段是强制性的,让系统在必要时调用它

在此之后,您可以在onCreateView或OnCreate方法中获取所需的参数...

答案 1 :(得分:0)

感谢所有提供的输入! 我通过调用片段方面的方法找到了一个干净的解决方案。简单愚蠢很棒。 我建议阅读以下文章:

https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments