我有ViewPager显示片段:SearchFragment,FriendFragment。我正在努力做的是将SearchFragment更改为ChatFragment
replace-fragment-inside-a-viewpager/中有很多反馈但我在使这些解决方案有效方面遇到了一些麻烦。
我认为我创建界面的方式可能有问题,我有一些麻烦让它可以从ViewPager调用<center>
我现在到达了
的地步java.lang.NullPointerException:尝试调用虚方法 “android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()'为null 对象参考 在 com.example.ashaneen.firebaseapp.adapters.MainScreenAdapter $ 1.onFragmentChange(MainScreenAdapter.java:44) 在 com.example.ashaneen.firebaseapp.fragments.SearchFragment $ 4.onComplete(SearchFragment.java:132)
MainScreenAdapter.class
SearchActivity.newInstance(new MyListener {...} )
SearchFragment.class
public class MainScreenAdapter extends FragmentPagerAdapter implements SearchFragment.MyListener {
private static final String TAG = "MainScreenAdapter";
private FragmentManager fragmentManager;
private Fragment fragment1;
public MainScreenAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
if (fragment1 == null)
{
fragment1 = SearchFragment.newInstance(new SearchFragment.MyListener() {
@Override
public void onFragmentChange() {
fragmentManager.beginTransaction().remove(fragment1).commit();
fragment1 = ChatFragment.newInstance();
notifyDataSetChanged();
}
});
}
return fragment1;
case 1:
return new FriendsFragment();
default:
return new ChatFragment();
}
}
@Override
public int getItemPosition(@NonNull Object object) {
return POSITION_NONE;
}
@Override
public void onFragmentChange() {
}
答案 0 :(得分:1)
尝试更改此
public MainScreenAdapter(FragmentManager fm) {
super(fm);
}
到
public MainScreenAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}