我的目标是在用户点击按钮时从ViewPager中删除片段。 填充ViewPager工作正常,但是当我尝试删除它时,我收到一个指示空引用的错误。我合并了Remove Fragment Page from ViewPager in Android
在我要删除的片段中,我有:
Button delete = (Button) getActivity().findViewById(R.id.dont_show_button_1);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db.deletePerson(count); // SQLiteDatabase, works fine
displayActivity.removeCurrentFragment(count-1);
}
});
DisplayActivity如下:
public class DisplayActivity extends FragmentActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
String TAG = "DisplayActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_layout);
viewPager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public void removeCurrentFragment(int position){
pagerAdapter.fragmentArrayList.remove(position);
pagerAdapter.notifyChangeInPosition(1);
pagerAdapter.notifyDataSetChanged();
Log.e(TAG, "in removeCurrentFragment");
}
}
PagerAdapter
public class PagerAdapter extends FragmentPagerAdapter {
long baseId = 0;
public static List<Fragment> fragmentArrayList = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager fm){
super(fm);
fragmentArrayList.add(new FragmentOne());
fragmentArrayList.add(new FragmentTwo());
fragmentArrayList.add(new FragmentThree());
}
@Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
@Override
public int getCount() {
return fragmentArrayList.size();
}
@Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
@Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
* @param n number of items which have been changed
*/
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
这是错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void .DisplayActivity.removeCurrentFragment(int)' on a null object reference
从片段
触发编辑:
public class FragmentOne extends Fragment {
DatabaseHelper db;
WebView mWebView;
DisplayActivity displayActivity;
int count = 1;
这是我从displayActivity获取引用的方式,这是获取引用的错误方法吗?
答案 0 :(得分:0)
if (count > 0) {
displayActivity.removeCurrentFragment(count - 1);
}