我使用ViewPager获得了一个Fragment,我得到了FragmentStatePagerAdapter,它在Fragment的OnCreateView()方法中初始化。为了设置数据,我在适配器中创建了方法setData(List<String> data)
:
public void setData(List<String> data) {
this.data = data;
notifyDataSetChanged();
}
在我使用ViewPager的片段中,我得到了:
public void setData(List<String> data){
adapter.setData(data);
setCurrentItem(0);
}
到目前为止一切正常,但是如果我在MainActivity中调用OnCreate():
fragment = (FragmentViewPager) getSupportFragmentManager().findFragmentByTag(TAG_VIEW_PAGER);
fragment.setData(myDataList);
它给出了Attempt to invoke virtual method ...setData(...) on a null object reference
错误,因为适配器尚未初始化。
我该如何解决这个问题?
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
showViewPager();
fragment = (FragmentViewPager) getSupportFragmentManager().findFragmentByTag(TAG_VIEW_PAGER);
fragment.setData(myDataList);
}
private void showViewPager() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = new FragmentViewPager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, TAG_VIEW_PAGER).commit();
fragmentManager.executePendingTransactions();
}
FragmentViewPager:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_view_pager, container, false);
viewPager = (ViewPager) layout.findViewById(R.id.pager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
return layout;
}
public void setData(List<String> data){
adapter.setData(data);
setCurrentItem(0);
}
public void setCurrentItem(int position) {
viewPager.setCurrentItem(position);
}
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<String> data;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void setData(List<String> data) {
this.data = data;
notifyDataSetChanged();
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new FragmentContent();
Bundle args = new Bundle();
args.putString(FragmentViewPager.ARG_STRING, data.get(i));
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
if (data != null) {
return data.size();
} else {
return 0;
}
}
@Override
public CharSequence getPageTitle(int position) {
return data.get(position);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
答案 0 :(得分:1)
我认为在片段中,您可以在setData()方法中声明一个List变量并将数据设置为此变量。
public void setData(List<String> data){
this.data = data;
}
然后在onCreateView()中,您将片段的数据变量设置为适配器。
adapter.setData(this.data);
我没有测试过,请在尝试时发表评论。 :)