gpt4 book ai didi

java - 更改 ViewPager 内显示的 fragment

转载 作者:行者123 更新时间:2023-12-02 11:45:52 25 4
gpt4 key购买 nike

我有 ViewPager 显示 fragment :SearchFragment、FriendFragment。我正在努力做的是将 SearchFragment 更改为 ChatFragment

replace-fragment-inside-a-viewpager/中有很多反馈但我在使这些解决方案发挥作用时遇到了一些麻烦。

我认为我创建界面的方式可能有问题,我在使其可从 ViewPager 调用时遇到了一些麻烦 SearchActivity.newInstance(new MyListener {...} )

我现在已经达到了我所得到的地步

java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()' on a null object reference at com.example.ashaneen.firebaseapp.adapters.MainScreenAdapter$1.onFragmentChange(MainScreenAdapter.java:44) at com.example.ashaneen.firebaseapp.fragments.SearchFragment$4.onComplete(SearchFragment.java:132)

MainScreenAdapter.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() {

}

SearchFragment.class

 public class SearchFragment extends android.support.v4.app.Fragment  {

public SearchFragment() {
}

private String TAG = "Profile2Fragment";

public interface MyListener
{
void onFragmentChange();
}

static MyListener myListener = new MyListener() {
public void onFragmentChange() {

}
};

public static SearchFragment newInstance(MyListener myListener) {

SearchFragment.myListener = myListener;
return new SearchFragment();
}
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);

button = view.findViewById(R.id.btn_search);
waitingRoomReference = db.collection("awaiting_room");




button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)

{
myListener.onFragmentChange();
}
}
});

return view;
}

最佳答案

尝试改变这个

public MainScreenAdapter(FragmentManager fm) {
super(fm);
}

public MainScreenAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}

关于java - 更改 ViewPager 内显示的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48207463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com