getArguments上的null引用

时间:2016-12-12 09:06:26

标签: java android

我有一个MainActivity(扩展Activity)和一个FooFragment(扩展Fragment)。

Activity使用newFooInstance方法实例化FooFragment并为其设置一些参数:

public static FooFragment newInstance(String label) {
    FooFragment fooFragment = new FooFragment();

    Bundle args = new Bundle();
    args.putString("fooLabel", label);
    fooFragment.setArguments(args);

    return fooFragment;
}

现在,在FooFragment s onCreateonCreateView里面我做了:

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

    fooLabel = getArguments().getString("fooLabel"); // null error
}

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_balanse_period, container, false
    );

    TextView fooView = (TextView) rootView.findViewById(R.id.fooLabel);
    fooView.setText(fooLabel);

    return rootView;
}

它产生:

  

尝试在空对象引用*

上调用虚方法java.lang.String android.os.Bundle.getString(java.lang.String, java.lang.String)

知道我做错了什么吗?

修改

将主要活动定义为:

public class MainActivity extends AppCompatActivity {

然后将fooFragment实例化为:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fragments = new ArrayList<>();
    fragments.add(newInstance("bar"));

    // Instantiate a ViewPager and PagerAdapter
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new FooPagerAdapter(getSupportFragmentManager(), fragments);

1 个答案:

答案 0 :(得分:0)

我找到了邪恶的根源。

FooPagerAdaptergetItem写错了。

<强>错误:

@Override
public Fragment getItem(int position) {
    return new FooFragment();
}

<强>正确:

@Override
public Fragment getItem(int position) {
    return fragments.get(position);
}