我有一个由ViewPager托管的片段
public class FragmentOne extends Fragment {
DatabaseHelper db;
String TAG = "FragmentOne";
DisplayActivity displayActivity;
....
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
displayActivity = new DisplayActivity();
initView();
}
Button delete = (Button) getActivity().findViewById(R.id.dont);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayActivity.removeCurrentFragment(count-1);
}
});
我的目标是从ViewPager中删除此当前片段。但是,通过调试器,我发现displayActivity为null。
如何获取displayActivity的参考资料?
public class DisplayActivity extends FragmentActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
String TAG = "DisplayActivity";
public void removeCurrentFragment(int position){
pagerAdapter.fragmentArrayList.remove(position);
pagerAdapter.notifyChangeInPosition(1);
pagerAdapter.notifyDataSetChanged();
Log.e(TAG, "in removeCurrentFragment");
}
我尝试使用displayActivity = new DisplayActivity(); 但似乎没有用。
这是错误
NullPointerException: Attempt to invoke virtual method 'void .DisplayActivity.removeCurrentFragment(int)' on a null object reference
答案 0 :(得分:1)
将getActivity()
与强制转换为DisplayActivity
。
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
displayActivity = (DisplayActivity) getActivity();
initView();
}