我有一个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 onCreate
和onCreateView
里面我做了:
@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);
答案 0 :(得分:0)
我找到了邪恶的根源。
在FooPagerAdapter
内getItem
写错了。
<强>错误:强>
@Override
public Fragment getItem(int position) {
return new FooFragment();
}
<强>正确:强>
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}